text
stringlengths
54
60.6k
<commit_before>/* Copyright (c) 2010, The Mineserver Project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the The Mineserver Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #ifdef WIN32 #include <conio.h> #include <winsock2.h> #include <process.h> #else #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <netdb.h> #include <unistd.h> #endif #include <sys/types.h> #include <fcntl.h> #include <cassert> #include <deque> #include <map> #include <iostream> #include <fstream> #include <event.h> #include <ctime> #include <vector> #include <zlib.h> #include <signal.h> #include "constants.h" #include "mineserver.h" #include "logger.h" #include "sockets.h" #include "tools.h" #include "map.h" #include "user.h" #include "chat.h" #include "worldgen/mapgen.h" #include "config.h" #include "nbt.h" #include "packets.h" #include "physics.h" #include "plugin.h" #ifdef WIN32 static bool quit = false; #endif int setnonblock(int fd) { #ifdef WIN32 u_long iMode = 1; ioctlsocket(fd, FIONBIO, &iMode); #else int flags; flags = fcntl(fd, F_GETFL); flags |= O_NONBLOCK; fcntl(fd, F_SETFL, flags); #endif return 1; } //Handle signals void sighandler(int sig_num) { Mineserver::Get().Stop(); } int main(int argc, char *argv[]) { signal(SIGTERM, sighandler); signal(SIGINT, sighandler); srand(time(NULL)); return Mineserver::Get().Run(argc, argv); } Mineserver::Mineserver() { } event_base *Mineserver::GetEventBase() { return m_eventBase; } int Mineserver::Run(int argc, char *argv[]) { uint32 starttime = (uint32)time(0); uint32 tick = (uint32)time(0); initConstants(); std::string file_config; file_config.assign(CONFIG_FILE); if (argc > 1) file_config.assign(argv[1]); // Initialize conf Conf::get()->load(file_config); // Write PID to file std::ofstream pid_out((Conf::get()->sValue("pid_file")).c_str()); if (!pid_out.fail()) #ifdef WIN32 pid_out << _getpid(); #else pid_out << getpid(); #endif pid_out.close(); // Load admin, banned and whitelisted users Chat::get()->loadAdmins(Conf::get()->sValue("admin_file")); Chat::get()->loadBanned(Conf::get()->sValue("banned_file")); Chat::get()->loadWhitelist(Conf::get()->sValue("whitelist_file")); // Load MOTD Chat::get()->checkMotd(Conf::get()->sValue("motd_file")); // Set physics enable state according to config Physics::get()->enabled = (Conf::get()->bValue("liquid_physics")); // Initialize map Map::get()->init(); if (Conf::get()->bValue("map_generate_spawn")) { std::cout << "Generating spawn area...\n"; for (int x=0;x<12;x++) for (int z=0;z<12;z++) Map::get()->loadMap(x-6, z-6); #ifdef _DEBUG std::cout << "Spawn area ready!\n"; #endif } // Initialize packethandler PacketHandler::get()->init(); // Load ip from config std::string ip = Conf::get()->sValue("ip"); // Load port from config int port = Conf::get()->iValue("port"); // Initialize plugins Plugin::get()->init(); #ifdef WIN32 WSADATA wsaData; int iResult; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if(iResult != 0) { printf("WSAStartup failed with error: %d\n", iResult); return EXIT_FAILURE; } #endif struct sockaddr_in addresslisten; int reuse = 1; m_eventBase = (event_base *)event_init(); #ifdef WIN32 m_socketlisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); #else m_socketlisten = socket(AF_INET, SOCK_STREAM, 0); #endif if(m_socketlisten < 0) { std::cerr << "Failed to create listen socket" << std::endl; return 1; } memset(&addresslisten, 0, sizeof(addresslisten)); addresslisten.sin_family = AF_INET; addresslisten.sin_addr.s_addr = inet_addr(ip.c_str()); addresslisten.sin_port = htons(port); setsockopt(m_socketlisten, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse)); //Bind to port if(bind(m_socketlisten, (struct sockaddr *)&addresslisten, sizeof(addresslisten)) < 0) { std::cerr << "Failed to bind" << std::endl; return 1; } if(listen(m_socketlisten, 5) < 0) { std::cerr << "Failed to listen to socket" << std::endl; return 1; } setnonblock(m_socketlisten); event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL); event_add(&m_listenEvent, NULL); std::cout << " _____ .__ "<< std::endl<< " / \\ |__| ____ ____ ______ ______________ __ ___________ "<< std::endl<< " / \\ / \\| |/ \\_/ __ \\ / ___// __ \\_ __ \\ \\/ // __ \\_ __ \\"<< std::endl<< "/ Y \\ | | \\ ___/ \\___ \\\\ ___/| | \\/\\ /\\ ___/| | \\/"<< std::endl<< "\\____|__ /__|___| /\\___ >____ >\\___ >__| \\_/ \\___ >__| "<< std::endl<< " \\/ \\/ \\/ \\/ \\/ \\/ "<< std::endl<< "Version " << VERSION <<" by The Mineserver Project"<< std::endl << std::endl; if(ip == "0.0.0.0") { // Print all local IPs char name[255]; gethostname ( name, sizeof(name)); struct hostent *hostinfo = gethostbyname(name); std::cout << "Listening on: "; int ipIndex = 0; while(hostinfo->h_addr_list[ipIndex]) { if(ipIndex > 0) { std::cout << ", "; } char *ip = inet_ntoa(*(struct in_addr *)hostinfo->h_addr_list[ipIndex++]); std::cout << ip << ":" << port; } std::cout << std::endl; } else { std::cout << "Listening on " << ip << ":" << port << std::endl; } std::cout << std::endl; timeval loopTime; loopTime.tv_sec = 0; loopTime.tv_usec = 200000; //200ms m_running=true; event_base_loopexit(m_eventBase, &loopTime); while(m_running && event_base_loop(m_eventBase, 0) == 0) { if(time(0)-starttime > 10) { starttime = (uint32)time(0); std::cout << "Currently " << Users.size() << " users in!" << std::endl; //If users, ping them if(Users.size() > 0) { //0x00 package uint8 data = 0; Users[0]->sendAll(&data, 1); //Send server time Packet pkt; pkt << (sint8)PACKET_TIME_UPDATE << (sint64)Map::get()->mapTime; Users[0]->sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen()); } //Try to load release time from config int map_release_time = Conf::get()->iValue("map_release_time"); //Release chunks not used in <map_release_time> seconds /* std::vector<uint32> toRelease; for(std::map<uint32, int>::const_iterator it = Map::get()->mapLastused.begin(); it != Map::get()->mapLastused.end(); ++it) { if(Map::get()->mapLastused[it->first] <= time(0)-map_release_time) toRelease.push_back(it->first); } int x_temp, z_temp; for(unsigned i = 0; i < toRelease.size(); i++) { Map::get()->idToPos(toRelease[i], &x_temp, &z_temp); Map::get()->releaseMap(x_temp, z_temp); } */ } //Every second if(time(0)-tick > 0) { tick = (uint32)time(0); //Loop users for(unsigned int i = 0; i < Users.size(); i++) { Users[i]->pushMap(); Users[i]->popMap(); //Minecart hacks!! if(Users[i]->attachedTo) { Packet pkt; pkt << PACKET_ENTITY_VELOCITY << (sint32)Users[i]->attachedTo << (sint16)10000 << (sint16)0 << (sint16)0; //pkt << PACKET_ENTITY_RELATIVE_MOVE << (sint32)Users[i]->attachedTo << (sint8)100 << (sint8)0 << (sint8)0; Users[i]->sendAll((uint8 *)pkt.getWrite(), pkt.getWriteLen()); } } Map::get()->mapTime+=20; if(Map::get()->mapTime>=24000) Map::get()->mapTime=0; } //Physics simulation every 200ms Physics::get()->update(); //Underwater check / drowning for( unsigned int i = 0; i < Users.size(); i++ ) Users[i]->isUnderwater(); event_base_loopexit(m_eventBase, &loopTime); } #ifdef WIN32 closesocket(m_socketlisten); #else close(m_socketlisten); #endif // Remove the PID file #ifdef WIN32 _unlink((Conf::get()->sValue("pid_file")).c_str()); #else unlink((Conf::get()->sValue("pid_file")).c_str()); #endif /* Free memory */ PacketHandler::get()->free(); Map::get()->free(); Physics::get()->free(); Chat::get()->free(); Conf::get()->free(); Plugin::get()->free(); Logger::get()->free(); MapGen::get()->free(); return EXIT_SUCCESS; } bool Mineserver::Stop() { m_running=false; return true; } <commit_msg>Old map release method no longer functional with chunk hash map<commit_after>/* Copyright (c) 2010, The Mineserver Project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the The Mineserver Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #ifdef WIN32 #include <conio.h> #include <winsock2.h> #include <process.h> #else #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <netdb.h> #include <unistd.h> #endif #include <sys/types.h> #include <fcntl.h> #include <cassert> #include <deque> #include <map> #include <iostream> #include <fstream> #include <event.h> #include <ctime> #include <vector> #include <zlib.h> #include <signal.h> #include "constants.h" #include "mineserver.h" #include "logger.h" #include "sockets.h" #include "tools.h" #include "map.h" #include "user.h" #include "chat.h" #include "worldgen/mapgen.h" #include "config.h" #include "nbt.h" #include "packets.h" #include "physics.h" #include "plugin.h" #ifdef WIN32 static bool quit = false; #endif int setnonblock(int fd) { #ifdef WIN32 u_long iMode = 1; ioctlsocket(fd, FIONBIO, &iMode); #else int flags; flags = fcntl(fd, F_GETFL); flags |= O_NONBLOCK; fcntl(fd, F_SETFL, flags); #endif return 1; } //Handle signals void sighandler(int sig_num) { Mineserver::Get().Stop(); } int main(int argc, char *argv[]) { signal(SIGTERM, sighandler); signal(SIGINT, sighandler); srand(time(NULL)); return Mineserver::Get().Run(argc, argv); } Mineserver::Mineserver() { } event_base *Mineserver::GetEventBase() { return m_eventBase; } int Mineserver::Run(int argc, char *argv[]) { uint32 starttime = (uint32)time(0); uint32 tick = (uint32)time(0); initConstants(); std::string file_config; file_config.assign(CONFIG_FILE); if (argc > 1) file_config.assign(argv[1]); // Initialize conf Conf::get()->load(file_config); // Write PID to file std::ofstream pid_out((Conf::get()->sValue("pid_file")).c_str()); if (!pid_out.fail()) #ifdef WIN32 pid_out << _getpid(); #else pid_out << getpid(); #endif pid_out.close(); // Load admin, banned and whitelisted users Chat::get()->loadAdmins(Conf::get()->sValue("admin_file")); Chat::get()->loadBanned(Conf::get()->sValue("banned_file")); Chat::get()->loadWhitelist(Conf::get()->sValue("whitelist_file")); // Load MOTD Chat::get()->checkMotd(Conf::get()->sValue("motd_file")); // Set physics enable state according to config Physics::get()->enabled = (Conf::get()->bValue("liquid_physics")); // Initialize map Map::get()->init(); if (Conf::get()->bValue("map_generate_spawn")) { std::cout << "Generating spawn area...\n"; for (int x=0;x<12;x++) for (int z=0;z<12;z++) Map::get()->loadMap(x-6, z-6); #ifdef _DEBUG std::cout << "Spawn area ready!\n"; #endif } // Initialize packethandler PacketHandler::get()->init(); // Load ip from config std::string ip = Conf::get()->sValue("ip"); // Load port from config int port = Conf::get()->iValue("port"); // Initialize plugins Plugin::get()->init(); #ifdef WIN32 WSADATA wsaData; int iResult; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if(iResult != 0) { printf("WSAStartup failed with error: %d\n", iResult); return EXIT_FAILURE; } #endif struct sockaddr_in addresslisten; int reuse = 1; m_eventBase = (event_base *)event_init(); #ifdef WIN32 m_socketlisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); #else m_socketlisten = socket(AF_INET, SOCK_STREAM, 0); #endif if(m_socketlisten < 0) { std::cerr << "Failed to create listen socket" << std::endl; return 1; } memset(&addresslisten, 0, sizeof(addresslisten)); addresslisten.sin_family = AF_INET; addresslisten.sin_addr.s_addr = inet_addr(ip.c_str()); addresslisten.sin_port = htons(port); setsockopt(m_socketlisten, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse)); //Bind to port if(bind(m_socketlisten, (struct sockaddr *)&addresslisten, sizeof(addresslisten)) < 0) { std::cerr << "Failed to bind" << std::endl; return 1; } if(listen(m_socketlisten, 5) < 0) { std::cerr << "Failed to listen to socket" << std::endl; return 1; } setnonblock(m_socketlisten); event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL); event_add(&m_listenEvent, NULL); std::cout << " _____ .__ "<< std::endl<< " / \\ |__| ____ ____ ______ ______________ __ ___________ "<< std::endl<< " / \\ / \\| |/ \\_/ __ \\ / ___// __ \\_ __ \\ \\/ // __ \\_ __ \\"<< std::endl<< "/ Y \\ | | \\ ___/ \\___ \\\\ ___/| | \\/\\ /\\ ___/| | \\/"<< std::endl<< "\\____|__ /__|___| /\\___ >____ >\\___ >__| \\_/ \\___ >__| "<< std::endl<< " \\/ \\/ \\/ \\/ \\/ \\/ "<< std::endl<< "Version " << VERSION <<" by The Mineserver Project"<< std::endl << std::endl; if(ip == "0.0.0.0") { // Print all local IPs char name[255]; gethostname ( name, sizeof(name)); struct hostent *hostinfo = gethostbyname(name); std::cout << "Listening on: "; int ipIndex = 0; while(hostinfo->h_addr_list[ipIndex]) { if(ipIndex > 0) { std::cout << ", "; } char *ip = inet_ntoa(*(struct in_addr *)hostinfo->h_addr_list[ipIndex++]); std::cout << ip << ":" << port; } std::cout << std::endl; } else { std::cout << "Listening on " << ip << ":" << port << std::endl; } std::cout << std::endl; timeval loopTime; loopTime.tv_sec = 0; loopTime.tv_usec = 200000; //200ms m_running=true; event_base_loopexit(m_eventBase, &loopTime); while(m_running && event_base_loop(m_eventBase, 0) == 0) { if(time(0)-starttime > 10) { starttime = (uint32)time(0); std::cout << "Currently " << Users.size() << " users in!" << std::endl; //If users, ping them if(Users.size() > 0) { //0x00 package uint8 data = 0; Users[0]->sendAll(&data, 1); //Send server time Packet pkt; pkt << (sint8)PACKET_TIME_UPDATE << (sint64)Map::get()->mapTime; Users[0]->sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen()); } //Try to load release time from config int map_release_time = Conf::get()->iValue("map_release_time"); //Release chunks not used in <map_release_time> seconds /* std::vector<uint32> toRelease; for(std::map<uint32, int>::const_iterator it = Map::get()->mapLastused.begin(); it != Map::get()->mapLastused.end(); ++it) { if(Map::get()->mapLastused[it->first] <= time(0)-map_release_time) toRelease.push_back(it->first); } int x_temp, z_temp; for(unsigned i = 0; i < toRelease.size(); i++) { Map::get()->idToPos(toRelease[i], &x_temp, &z_temp); Map::get()->releaseMap(x_temp, z_temp); } } */ //Every second if(time(0)-tick > 0) { tick = (uint32)time(0); //Loop users for(unsigned int i = 0; i < Users.size(); i++) { Users[i]->pushMap(); Users[i]->popMap(); //Minecart hacks!! if(Users[i]->attachedTo) { Packet pkt; pkt << PACKET_ENTITY_VELOCITY << (sint32)Users[i]->attachedTo << (sint16)10000 << (sint16)0 << (sint16)0; //pkt << PACKET_ENTITY_RELATIVE_MOVE << (sint32)Users[i]->attachedTo << (sint8)100 << (sint8)0 << (sint8)0; Users[i]->sendAll((uint8 *)pkt.getWrite(), pkt.getWriteLen()); } } Map::get()->mapTime+=20; if(Map::get()->mapTime>=24000) Map::get()->mapTime=0; } //Physics simulation every 200ms Physics::get()->update(); //Underwater check / drowning for( unsigned int i = 0; i < Users.size(); i++ ) Users[i]->isUnderwater(); event_base_loopexit(m_eventBase, &loopTime); } #ifdef WIN32 closesocket(m_socketlisten); #else close(m_socketlisten); #endif // Remove the PID file #ifdef WIN32 _unlink((Conf::get()->sValue("pid_file")).c_str()); #else unlink((Conf::get()->sValue("pid_file")).c_str()); #endif /* Free memory */ PacketHandler::get()->free(); Map::get()->free(); Physics::get()->free(); Chat::get()->free(); Conf::get()->free(); Plugin::get()->free(); Logger::get()->free(); MapGen::get()->free(); return EXIT_SUCCESS; } bool Mineserver::Stop() { m_running=false; return true; } <|endoftext|>
<commit_before>/* * car.cpp * * Author: Ming Tsang * Copyright (c) 2014 HKUST SmartCar Team * Refer to LICENSE for details */ #include <cstddef> #include <memory> #include <libsc/k60/encoder.h> #include <libsc/k60/led.h> #include <libsc/k60/motor.h> #include <libsc/k60/simple_buzzer.h> #include <libsc/k60/trs_d05.h> #include <libsc/k60/uart_device.h> #include <libutil/misc.h> #include <libutil/remote_var_manager.h> #include "car.h" using namespace libsc::k60; using namespace std; #define SERVO_MID_DEGREE 815 #define SERVO_AMPLITUDE 290 namespace inno { Car::Car() : m_encoder(0), m_leds{Led(0), Led(1), Led(2), Led(3)}, m_motor(0, false), m_buzzer({0, false}), m_servo(0), m_uart(0, libbase::k60::Uart::Config::BaudRate::k115200) {} Car::~Car() {} void Car::SetMotorPower(const int16_t power) { const Uint power_ = libutil::Clamp<Uint>(0, abs(power), 1000); m_motor.SetClockwise(power < 0); m_motor.SetPower(power_); } void Car::SetTurning(const int16_t percentage) { // Servo's rotation dir is opposite to our wheels const int percentage_ = libutil::Clamp<int>(-100, -percentage, 100); const int degree = SERVO_MID_DEGREE + (percentage_ * SERVO_AMPLITUDE / 1000); m_servo.SetDegree(degree); } } <commit_msg>Update to be compatible to buzzer<commit_after>/* * car.cpp * * Author: Ming Tsang * Copyright (c) 2014 HKUST SmartCar Team * Refer to LICENSE for details */ #include <cstddef> #include <memory> #include <libsc/k60/encoder.h> #include <libsc/k60/led.h> #include <libsc/k60/motor.h> #include <libsc/k60/simple_buzzer.h> #include <libsc/k60/trs_d05.h> #include <libsc/k60/uart_device.h> #include <libutil/misc.h> #include <libutil/remote_var_manager.h> #include "car.h" using namespace libsc::k60; using namespace std; #define SERVO_MID_DEGREE 815 #define SERVO_AMPLITUDE 290 namespace inno { Car::Car() : m_encoder(0), m_leds{Led(0), Led(1), Led(2), Led(3)}, m_motor(0, false), m_buzzer({0}), m_servo(0), m_uart(0, libbase::k60::Uart::Config::BaudRate::k115200) {} Car::~Car() {} void Car::SetMotorPower(const int16_t power) { const Uint power_ = libutil::Clamp<Uint>(0, abs(power), 1000); m_motor.SetClockwise(power < 0); m_motor.SetPower(power_); } void Car::SetTurning(const int16_t percentage) { // Servo's rotation dir is opposite to our wheels const int percentage_ = libutil::Clamp<int>(-100, -percentage, 100); const int degree = SERVO_MID_DEGREE + (percentage_ * SERVO_AMPLITUDE / 1000); m_servo.SetDegree(degree); } } <|endoftext|>
<commit_before>#include <event2/event.h> #include <string> #include "city.h" #include "event_manager.h" int City::cache_[] = {5, 15, 45, 135}; double City::defense_multiplier[] = {1.1, 1.15, 1.2, 1.25}; city_id City::INVALID_CITY = -1; city_id City::current_id = -1; City * City::winning_city; int City::incomes_[] = {1, 2, 3, 5}; int City::upgrade_costs_[] = {30, 90, 270, 810}; int City::upgrade_times_[] = {10, 20, 30, 40}; int City::train_time_ = 5; int City::train_cost_ = 5; int City::MAX_LEVEL = 5; city_id City::get_next_city_id() { current_id++; return current_id; } std::string City::city_id_string(city_id id) { return std::to_string(id); } City::City(std::string name, city_id id) { level_ = 1; gold_ = 0.0; soldiers_ = 0; name_ = name; id_ = id; upgrading_ = false; } void City::set_start_time(std::chrono::steady_clock::time_point time) { last_income_ = time; } void City::update_gold() { std::chrono::duration<double> diff = std::chrono::steady_clock::now() - last_income_; double delta_sec = diff.count(); double delta_gold = delta_sec * incomes_[level_ - 1]; if (delta_gold >= 1) { gold_ += delta_gold; last_income_ = std::chrono::steady_clock::now(); } } int City::get_gold() { update_gold(); return int(gold_); } int City::change_gold(int delta) { int gold = get_gold(); if (delta >= 0) { gold_ += delta; return -delta; } int new_gold = gold + delta; int cache = cache_[level_ - 1]; if (new_gold >= cache) { gold_ += delta; return -delta; } else { if (cache > gold) { return 0; } else { gold_ = gold_ - gold + cache; return gold - cache; } } } std::string City::get_name() { return name_; } void City::set_location(Location* l) { loc_ = l; } Location City::get_location() { return *loc_; } void City::add_neighbor(City* neighbor, float distance) { neighbors_.insert(std::pair<City*, float>(neighbor, distance)); } std::string City::display_all_neighbor_info() { std::string info_str = ""; for (auto it = neighbors_.begin(); it != neighbors_.end(); it++) { if (it->first) { City& other_city = *(it->first); // id [id] [other name] [other level] [distance from this to other] info_str += other_city.get_name(); info_str += " (" + std::to_string(other_city.get_id()) + ") "; info_str += std::to_string(other_city.level_) + "\n"; } } return info_str; } float City::distance_to(City *other_city) { auto it = neighbors_.find(other_city); if (it == neighbors_.end()) { return 0.0; } return it->second; } std::string City::info(bool less) { std::string info = ""; std::string delim = ""; if (!less) { delim = "\n"; } info += name_ + delim; info += " LEVEL " + std::to_string(level_) + delim; info += " GOLD " + std::to_string(get_gold()) + delim; info += " INCOME " + std::to_string(incomes_[level_ - 1]) + delim; info += " ARMY " + std::to_string(soldiers_) + "\n"; if (!less) { for (auto it = notifications_.rbegin(); it != notifications_.rend(); it++) { info += " " + notification_to_string(it->first, it->second); info += "\n"; } } return info; } std::string City::notification_to_string(std::chrono::steady_clock::time_point& time, std::string& contents) { std::chrono::duration<double> diff = std::chrono::steady_clock::now() - time; // TODO: int or double precision? return "* " + std::to_string(int(diff.count())) + " sec ago: " + contents; } void City::add_attack_notification(bool defending, std::string attack_city, int n_attackers, int n_attackers_remaining, int gold_stolen, int n_defenders, int n_defenders_remaining) { std::string contents = ""; if (defending) { contents += attack_city + " attacked "; } else { contents += "attacked " + attack_city + " "; } contents += std::to_string(n_attackers_remaining); contents += "/" + std::to_string(n_attackers) + " took "; contents += std::to_string(gold_stolen) + " gold"; if (defending || n_attackers_remaining > 0) { contents += ", " + std::to_string(n_defenders_remaining) + "/"; contents += std::to_string(n_defenders) + " defenders remained"; } notifications_.push_back( std::pair<std::chrono::steady_clock::time_point, std::string> (std::chrono::steady_clock::now(), contents) ); } void City::clear_notifications(int keep) { int to_remove = int(notifications_.size()) - keep; if (to_remove <= 0) { return; } notifications_.erase(notifications_.begin(), notifications_.begin() + to_remove); } int City::get_level() { return level_; } std::string City::costs() { std::string costs = ""; costs += "UPGRADE " + std::to_string(upgrade_costs_[level_ - 1]); costs += " gold, " + std::to_string(upgrade_times_[level_ - 1]) + " sec\n"; costs += "TRAIN " + std::to_string(train_cost_); costs += " gold, " + std::to_string(train_time_) + " sec\n"; return costs; } struct upgrade_arg { City *city; struct event *event_p; }; void City::increase_level() { level_++; } void City::finish_upgrading() { upgrading_ = false; } void City::upgrade_callback(evutil_socket_t listener, short event, void *arg) { (void)(event); // UNUSED (void)(listener); // UNUSED struct upgrade_arg *upgrade_args = (struct upgrade_arg *) arg; upgrade_args->city->increase_level(); if (upgrade_args->city->get_level() == City::MAX_LEVEL && !winning_city) { winning_city = upgrade_args->city; EventManager::trigger_end_game(); } upgrade_args->city->finish_upgrading(); event_free(upgrade_args->event_p); delete upgrade_args; } std::string City::upgrade() { int gold = get_gold(); int upgrade_cost = upgrade_costs_[level_ - 1]; if (level_ == City::MAX_LEVEL) { return "UPGRADE FAILURE MAX LEVEL\n"; } if (upgrading_) { return "UPGRADE FAILURE already upgrading\n"; } if (gold >= upgrade_cost) { gold_ -= upgrade_cost; upgrading_ = true; // create and add an event to train soldiers after train_time_ struct timeval tv; tv.tv_sec = upgrade_times_[level_ - 1]; tv.tv_usec = 0; struct upgrade_arg *upgrade_args = new upgrade_arg; upgrade_args->city = this; struct event *upgrade_event; upgrade_event = evtimer_new(EventManager::base, upgrade_callback, (void *) upgrade_args); upgrade_args->event_p = upgrade_event; evtimer_add(upgrade_event, &tv); return "UPGRADE SUCCESS\n"; } std::string response = "UPGRADE FAILURE "; response += std::to_string(upgrade_cost) + " > " + std::to_string(gold); response += "\n"; return response; } std::string City::train_max() { int num_soldiers = get_gold() / train_cost_; if (num_soldiers == 0) { return "TRAIN FAILURE Cannot train 0 soldiers\n"; } return train(num_soldiers); } struct train_arg { City *city; int num_soldiers; struct event *event_p; }; void City::train_callback(evutil_socket_t listener, short event, void *arg) { (void)(event); // UNUSED (void)(listener); // UNUSED struct train_arg *train_args = (struct train_arg *) arg; train_args->city->change_soldiers(train_args->num_soldiers); event_free(train_args->event_p); delete train_args; } std::string City::train(int num_soldiers) { int gold = get_gold(); int train_cost = num_soldiers * train_cost_; if (gold >= train_cost) { gold_ -= train_cost; // create and add an event to train soldiers after train_time_ struct timeval tv; tv.tv_sec = train_time_; tv.tv_usec = 0; struct train_arg *train_args = new train_arg; train_args->city = this; train_args->num_soldiers = num_soldiers; struct event *train_event; train_event = evtimer_new(EventManager::base, train_callback, (void *) train_args); train_args->event_p = train_event; evtimer_add(train_event, &tv); return "TRAIN " + std::to_string(num_soldiers) + " SUCCESS\n"; } std::string response = "TRAIN FAILURE "; response += std::to_string(num_soldiers) + " COSTS "; response += std::to_string(train_cost) + " > " + std::to_string(gold); response += "\n"; return response; } int City::get_soldiers() { return soldiers_; } void City::change_soldiers(int n) { soldiers_ += n; } void City::set_soldiers(int n) { if (n >= 0) { soldiers_ = n; } } city_id City::get_id() { return id_; } <commit_msg>change soldiers more safely<commit_after>#include <event2/event.h> #include <string> #include "city.h" #include "event_manager.h" int City::cache_[] = {5, 15, 45, 135}; double City::defense_multiplier[] = {1.1, 1.15, 1.2, 1.25}; city_id City::INVALID_CITY = -1; city_id City::current_id = -1; City * City::winning_city; int City::incomes_[] = {1, 2, 3, 5}; int City::upgrade_costs_[] = {30, 90, 270, 810}; int City::upgrade_times_[] = {10, 20, 30, 40}; int City::train_time_ = 5; int City::train_cost_ = 5; int City::MAX_LEVEL = 5; city_id City::get_next_city_id() { current_id++; return current_id; } std::string City::city_id_string(city_id id) { return std::to_string(id); } City::City(std::string name, city_id id) { level_ = 1; gold_ = 0.0; soldiers_ = 0; name_ = name; id_ = id; upgrading_ = false; } void City::set_start_time(std::chrono::steady_clock::time_point time) { last_income_ = time; } void City::update_gold() { std::chrono::duration<double> diff = std::chrono::steady_clock::now() - last_income_; double delta_sec = diff.count(); double delta_gold = delta_sec * incomes_[level_ - 1]; if (delta_gold >= 1) { gold_ += delta_gold; last_income_ = std::chrono::steady_clock::now(); } } int City::get_gold() { update_gold(); return int(gold_); } int City::change_gold(int delta) { int gold = get_gold(); if (delta >= 0) { gold_ += delta; return -delta; } int new_gold = gold + delta; int cache = cache_[level_ - 1]; if (new_gold >= cache) { gold_ += delta; return -delta; } else { if (cache > gold) { return 0; } else { gold_ = gold_ - gold + cache; return gold - cache; } } } std::string City::get_name() { return name_; } void City::set_location(Location* l) { loc_ = l; } Location City::get_location() { return *loc_; } void City::add_neighbor(City* neighbor, float distance) { neighbors_.insert(std::pair<City*, float>(neighbor, distance)); } std::string City::display_all_neighbor_info() { std::string info_str = ""; for (auto it = neighbors_.begin(); it != neighbors_.end(); it++) { if (it->first) { City& other_city = *(it->first); // id [id] [other name] [other level] [distance from this to other] info_str += other_city.get_name(); info_str += " (" + std::to_string(other_city.get_id()) + ") "; info_str += std::to_string(other_city.level_) + "\n"; } } return info_str; } float City::distance_to(City *other_city) { auto it = neighbors_.find(other_city); if (it == neighbors_.end()) { return 0.0; } return it->second; } std::string City::info(bool less) { std::string info = ""; std::string delim = ""; if (!less) { delim = "\n"; } info += name_ + delim; info += " LEVEL " + std::to_string(level_) + delim; info += " GOLD " + std::to_string(get_gold()) + delim; info += " INCOME " + std::to_string(incomes_[level_ - 1]) + delim; info += " ARMY " + std::to_string(soldiers_) + "\n"; if (!less) { for (auto it = notifications_.rbegin(); it != notifications_.rend(); it++) { info += " " + notification_to_string(it->first, it->second); info += "\n"; } } return info; } std::string City::notification_to_string(std::chrono::steady_clock::time_point& time, std::string& contents) { std::chrono::duration<double> diff = std::chrono::steady_clock::now() - time; // TODO: int or double precision? return "* " + std::to_string(int(diff.count())) + " sec ago: " + contents; } void City::add_attack_notification(bool defending, std::string attack_city, int n_attackers, int n_attackers_remaining, int gold_stolen, int n_defenders, int n_defenders_remaining) { std::string contents = ""; if (defending) { contents += attack_city + " attacked "; } else { contents += "attacked " + attack_city + " "; } contents += std::to_string(n_attackers_remaining); contents += "/" + std::to_string(n_attackers) + " took "; contents += std::to_string(gold_stolen) + " gold"; if (defending || n_attackers_remaining > 0) { contents += ", " + std::to_string(n_defenders_remaining) + "/"; contents += std::to_string(n_defenders) + " defenders remained"; } notifications_.push_back( std::pair<std::chrono::steady_clock::time_point, std::string> (std::chrono::steady_clock::now(), contents) ); } void City::clear_notifications(int keep) { int to_remove = int(notifications_.size()) - keep; if (to_remove <= 0) { return; } notifications_.erase(notifications_.begin(), notifications_.begin() + to_remove); } int City::get_level() { return level_; } std::string City::costs() { std::string costs = ""; costs += "UPGRADE " + std::to_string(upgrade_costs_[level_ - 1]); costs += " gold, " + std::to_string(upgrade_times_[level_ - 1]) + " sec\n"; costs += "TRAIN " + std::to_string(train_cost_); costs += " gold, " + std::to_string(train_time_) + " sec\n"; return costs; } struct upgrade_arg { City *city; struct event *event_p; }; void City::increase_level() { level_++; } void City::finish_upgrading() { upgrading_ = false; } void City::upgrade_callback(evutil_socket_t listener, short event, void *arg) { (void)(event); // UNUSED (void)(listener); // UNUSED struct upgrade_arg *upgrade_args = (struct upgrade_arg *) arg; upgrade_args->city->increase_level(); if (upgrade_args->city->get_level() == City::MAX_LEVEL && !winning_city) { winning_city = upgrade_args->city; EventManager::trigger_end_game(); } upgrade_args->city->finish_upgrading(); event_free(upgrade_args->event_p); delete upgrade_args; } std::string City::upgrade() { int gold = get_gold(); int upgrade_cost = upgrade_costs_[level_ - 1]; if (level_ == City::MAX_LEVEL) { return "UPGRADE FAILURE MAX LEVEL\n"; } if (upgrading_) { return "UPGRADE FAILURE already upgrading\n"; } if (gold >= upgrade_cost) { gold_ -= upgrade_cost; upgrading_ = true; // create and add an event to train soldiers after train_time_ struct timeval tv; tv.tv_sec = upgrade_times_[level_ - 1]; tv.tv_usec = 0; struct upgrade_arg *upgrade_args = new upgrade_arg; upgrade_args->city = this; struct event *upgrade_event; upgrade_event = evtimer_new(EventManager::base, upgrade_callback, (void *) upgrade_args); upgrade_args->event_p = upgrade_event; evtimer_add(upgrade_event, &tv); return "UPGRADE SUCCESS\n"; } std::string response = "UPGRADE FAILURE "; response += std::to_string(upgrade_cost) + " > " + std::to_string(gold); response += "\n"; return response; } std::string City::train_max() { int num_soldiers = get_gold() / train_cost_; if (num_soldiers == 0) { return "TRAIN FAILURE Cannot train 0 soldiers\n"; } return train(num_soldiers); } struct train_arg { City *city; int num_soldiers; struct event *event_p; }; void City::train_callback(evutil_socket_t listener, short event, void *arg) { (void)(event); // UNUSED (void)(listener); // UNUSED struct train_arg *train_args = (struct train_arg *) arg; train_args->city->change_soldiers(train_args->num_soldiers); event_free(train_args->event_p); delete train_args; } std::string City::train(int num_soldiers) { int gold = get_gold(); int train_cost = num_soldiers * train_cost_; if (gold >= train_cost) { gold_ -= train_cost; // create and add an event to train soldiers after train_time_ struct timeval tv; tv.tv_sec = train_time_; tv.tv_usec = 0; struct train_arg *train_args = new train_arg; train_args->city = this; train_args->num_soldiers = num_soldiers; struct event *train_event; train_event = evtimer_new(EventManager::base, train_callback, (void *) train_args); train_args->event_p = train_event; evtimer_add(train_event, &tv); return "TRAIN " + std::to_string(num_soldiers) + " SUCCESS\n"; } std::string response = "TRAIN FAILURE "; response += std::to_string(num_soldiers) + " COSTS "; response += std::to_string(train_cost) + " > " + std::to_string(gold); response += "\n"; return response; } int City::get_soldiers() { return soldiers_; } void City::change_soldiers(int n) { set_soldiers(soldiers_ + n); } void City::set_soldiers(int n) { if (n >= 0) { soldiers_ = n; } } city_id City::get_id() { return id_; } <|endoftext|>
<commit_before>/* * ModSecurity, http://www.modsecurity.org/ * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/) * * 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 * * If any of the files related to licensing are missing or if you have any * other questions related to licensing please contact Trustwave Holdings, Inc. * directly using the email address [email protected]. * */ #include <ctime> #include <iostream> #include "modsecurity/modsecurity.h" #include "src/rule.h" #include "src/config.h" #include "src/unique_id.h" #ifdef MSC_WITH_CURL #include <curl/curl.h> #endif #include "utils/geo_lookup.h" namespace ModSecurity { /** * @name ModSecurity * @brief Initilizes ModSecurity CPP API * * ModSecurity initializer. * * Example Usage: * @code * * using ModSecurity::ModSecurity; * * ModSecurity *msc = new ModSecurity(); * * @endcode */ ModSecurity::ModSecurity() : m_connector(""), m_logCb(NULL) { UniqueId::uniqueId(); srand(time(NULL)); #ifdef MSC_WITH_CURL curl_global_init(CURL_GLOBAL_ALL); #endif } ModSecurity::~ModSecurity() { #ifdef MSC_WITH_CURL curl_global_cleanup(); #endif Utils::GeoLookup::getInstance().cleanUp(); } /** * @name whoAmI * @brief Return information about this ModSecurity version and platform. * * Platform and version are two questions that community will ask prior to * provide support. Making it available internally and to the connector as * well. * * @note This information maybe will be used by a log parser. If you want to * update it, make it in a fashion that won't break the existent parsers. * (e.g. adding extra information _only_ to the end of the string) */ std::string ModSecurity::whoAmI() { std::string platform("Unknown platform"); #if AIX platform = "AIX"; #elif LINUX platform = "Linux"; #elif OPENBSD platform = "OpenBSD"; #elif SOLARIS platform = "Solaris"; #elif HPUX platform = "HPUX"; #elif MACOSX platform = "MacOSX"; #elif FREEBSD platform = "FreeBSD"; #elif NETBSD platform = "NetBSD"; #elif WIN32 platform = "Windows"; #endif return std::string("ModSecurity v" MODSECURITY_VERSION \ " (" + platform + ")"); } /** * @name setConnectorInformation * @brief Set information about the connector that is using the library. * * For the purpose of log it is necessary for modsecurity to understand which * 'connector' is consuming the API. * * @note It is strongly recommended to set a information in the following * pattern: * * ConnectorName vX.Y.Z-tag (something else) * * For instance: ModSecurity-nginx v0.0.1-alpha (Whee) * * @param connector Information about the connector. * */ void ModSecurity::setConnectorInformation(std::string connector) { m_connector = connector; } /** * @name getConnectorInformation * @brief Returns the connector information. * * Returns whatever was set by 'setConnectorInformation'. Check * setConnectorInformation documentation to understand the expected format. * * @retval "" Nothing was informed about the connector. * @retval !="" Connector information. */ const std::string& ModSecurity::getConnectorInformation() { return m_connector; } void ModSecurity::serverLog(void *data, const std::string& msg) { if (m_logCb == NULL) { std::cout << "Server log callback is not set -- " << msg << std::endl; } else { m_logCb(data, msg.c_str()); } } void ModSecurity::setServerLogCb(LogCb cb) { m_logCb = (LogCb) cb; } extern "C" void msc_set_log_cb(ModSecurity *msc, LogCb cb) { msc->setServerLogCb(cb); } /** * @name msc_set_connector_info * @brief Set information about the connector that is using the library. * * For the purpose of log it is necessary for modsecurity to understand which * 'connector' is consuming the API. * * @note It is strongly recommended to set a information in the following * pattern: * * ConnectorName vX.Y.Z-tag (something else) * * For instance: ModSecurity-nginx v0.0.1-alpha * * @param connector Information about the connector. * */ extern "C" void msc_set_connector_info(ModSecurity *msc, const char *connector) { msc->setConnectorInformation(std::string(connector)); } /** * @name msc_who_am_i * @brief Return information about this ModSecurity version and platform. * * Platform and version are two questions that community will ask prior to * provide support. Making it available internally and to the connector as * well. * * @note This information maybe will be used by a log parser. If you want to * update it, make it in a fashion that won't break the existent parsers. * (e.g. adding extra information _only_ to the end of the string) */ extern "C" const char *msc_who_am_i(ModSecurity *msc) { return msc->whoAmI().c_str(); } /** * @name msc_cleanup * @brief Cleanup ModSecurity C API * * Cleanup ModSecurity instance. * */ extern "C" void msc_cleanup(ModSecurity *msc) { delete msc; } /** * @name msc_init * @brief Initilizes ModSecurity C API * * ModSecurity initializer. * * Example Usage: * @code * * ModSecurity msc = msc_init(); * * @endcode */ extern "C" ModSecurity *msc_init() { ModSecurity *modsec = new ModSecurity(); return modsec; } } // namespace ModSecurity <commit_msg>Added some comments about msc_set_log_cb<commit_after>/* * ModSecurity, http://www.modsecurity.org/ * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/) * * 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 * * If any of the files related to licensing are missing or if you have any * other questions related to licensing please contact Trustwave Holdings, Inc. * directly using the email address [email protected]. * */ #include <ctime> #include <iostream> #include "modsecurity/modsecurity.h" #include "src/rule.h" #include "src/config.h" #include "src/unique_id.h" #ifdef MSC_WITH_CURL #include <curl/curl.h> #endif #include "utils/geo_lookup.h" namespace ModSecurity { /** * @name ModSecurity * @brief Initilizes ModSecurity CPP API * * ModSecurity initializer. * * Example Usage: * @code * * using ModSecurity::ModSecurity; * * ModSecurity *msc = new ModSecurity(); * * @endcode */ ModSecurity::ModSecurity() : m_connector(""), m_logCb(NULL) { UniqueId::uniqueId(); srand(time(NULL)); #ifdef MSC_WITH_CURL curl_global_init(CURL_GLOBAL_ALL); #endif } ModSecurity::~ModSecurity() { #ifdef MSC_WITH_CURL curl_global_cleanup(); #endif Utils::GeoLookup::getInstance().cleanUp(); } /** * @name whoAmI * @brief Return information about this ModSecurity version and platform. * * Platform and version are two questions that community will ask prior to * provide support. Making it available internally and to the connector as * well. * * @note This information maybe will be used by a log parser. If you want to * update it, make it in a fashion that won't break the existent parsers. * (e.g. adding extra information _only_ to the end of the string) */ std::string ModSecurity::whoAmI() { std::string platform("Unknown platform"); #if AIX platform = "AIX"; #elif LINUX platform = "Linux"; #elif OPENBSD platform = "OpenBSD"; #elif SOLARIS platform = "Solaris"; #elif HPUX platform = "HPUX"; #elif MACOSX platform = "MacOSX"; #elif FREEBSD platform = "FreeBSD"; #elif NETBSD platform = "NetBSD"; #elif WIN32 platform = "Windows"; #endif return std::string("ModSecurity v" MODSECURITY_VERSION \ " (" + platform + ")"); } /** * @name setConnectorInformation * @brief Set information about the connector that is using the library. * * For the purpose of log it is necessary for modsecurity to understand which * 'connector' is consuming the API. * * @note It is strongly recommended to set a information in the following * pattern: * * ConnectorName vX.Y.Z-tag (something else) * * For instance: ModSecurity-nginx v0.0.1-alpha (Whee) * * @param connector Information about the connector. * */ void ModSecurity::setConnectorInformation(std::string connector) { m_connector = connector; } /** * @name getConnectorInformation * @brief Returns the connector information. * * Returns whatever was set by 'setConnectorInformation'. Check * setConnectorInformation documentation to understand the expected format. * * @retval "" Nothing was informed about the connector. * @retval !="" Connector information. */ const std::string& ModSecurity::getConnectorInformation() { return m_connector; } void ModSecurity::serverLog(void *data, const std::string& msg) { if (m_logCb == NULL) { std::cout << "Server log callback is not set -- " << msg << std::endl; } else { m_logCb(data, msg.c_str()); } } void ModSecurity::setServerLogCb(LogCb cb) { m_logCb = (LogCb) cb; } /** * @name msc_set_log_cb * @brief Set the log callback functiond * * It is neccessary to indicate to libModSecurity which function within the * connector should be called when logging is required. * * @oarm msc The current ModSecurity instance * @param LogCB The callback function to which a reference to the log msgs * will be passed. * */ extern "C" void msc_set_log_cb(ModSecurity *msc, LogCb cb) { msc->setServerLogCb(cb); } /** * @name msc_set_connector_info * @brief Set information about the connector that is using the library. * * For the purpose of log it is necessary for modsecurity to understand which * 'connector' is consuming the API. * * @note It is strongly recommended to set a information in the following * pattern: * * ConnectorName vX.Y.Z-tag (something else) * * For instance: ModSecurity-nginx v0.0.1-alpha * * @param connector Information about the connector. * */ extern "C" void msc_set_connector_info(ModSecurity *msc, const char *connector) { msc->setConnectorInformation(std::string(connector)); } /** * @name msc_who_am_i * @brief Return information about this ModSecurity version and platform. * * Platform and version are two questions that community will ask prior to * provide support. Making it available internally and to the connector as * well. * * @note This information maybe will be used by a log parser. If you want to * update it, make it in a fashion that won't break the existent parsers. * (e.g. adding extra information _only_ to the end of the string) */ extern "C" const char *msc_who_am_i(ModSecurity *msc) { return msc->whoAmI().c_str(); } /** * @name msc_cleanup * @brief Cleanup ModSecurity C API * * Cleanup ModSecurity instance. * */ extern "C" void msc_cleanup(ModSecurity *msc) { delete msc; } /** * @name msc_init * @brief Initilizes ModSecurity C API * * ModSecurity initializer. * * Example Usage: * @code * * ModSecurity msc = msc_init(); * * @endcode */ extern "C" ModSecurity *msc_init() { ModSecurity *modsec = new ModSecurity(); return modsec; } } // namespace ModSecurity <|endoftext|>
<commit_before>/* ** Copyright 2009-2011 MERETHIS ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. ** ** For more information: [email protected] */ #include <stddef.h> #include "config/parser.hh" #include "config/state.hh" #include "init.hh" #include "logging/logging.hh" #include "logging/syslogger.hh" #include "module/callbacks.hh" #include "module/internal.hh" #include "nagios/common.h" #include "nagios/nebcallbacks.h" using namespace com::centreon::broker; /************************************** * * * Global Objects * * * **************************************/ // Specify the event broker API version. NEB_API_VERSION(CURRENT_NEB_API_VERSION) // Configuration file name. QString module::gl_configuration_file; // List of host IDs. std::map<std::string, int> module::gl_hosts; // List of service IDs. std::map<std::pair<std::string, std::string>, std::pair<int, int> > module::gl_services; // Sender object. multiplexing::publisher module::gl_publisher; /************************************** * * * Static Objects * * * **************************************/ // List of callbacks static struct { unsigned int macro; int (* callback)(int, void*); bool registered; } gl_callbacks[] = { { NEBCALLBACK_ACKNOWLEDGEMENT_DATA, &module::callback_acknowledgement, false }, { NEBCALLBACK_COMMENT_DATA, &module::callback_comment, false }, { NEBCALLBACK_DOWNTIME_DATA, &module::callback_downtime, false }, { NEBCALLBACK_EVENT_HANDLER_DATA, &module::callback_event_handler, false }, { NEBCALLBACK_FLAPPING_DATA, &module::callback_flapping_status, false }, { NEBCALLBACK_HOST_CHECK_DATA, &module::callback_host_check, false }, { NEBCALLBACK_HOST_STATUS_DATA, &module::callback_host_status, false }, { NEBCALLBACK_LOG_DATA, &module::callback_log, false }, { NEBCALLBACK_PROCESS_DATA, &module::callback_process, false }, { NEBCALLBACK_PROGRAM_STATUS_DATA, &module::callback_program_status, false }, { NEBCALLBACK_SERVICE_CHECK_DATA, &module::callback_service_check, false }, { NEBCALLBACK_SERVICE_STATUS_DATA, &module::callback_service_status, false } }; // Module handle static void* gl_mod_handle = NULL; /************************************** * * * Static Functions * * * **************************************/ /** * @brief Deregister callbacks. * * Deregister all callbacks previously registered. */ static void deregister_callbacks() { for (unsigned int i = 0; i < sizeof(gl_callbacks) / sizeof(*gl_callbacks); ++i) if (gl_callbacks[i].registered) { neb_deregister_callback(gl_callbacks[i].macro, gl_callbacks[i].callback); gl_callbacks[i].registered = false; } return ; } /************************************** * * * Exported Functions * * * **************************************/ extern "C" { /** * @brief Module exit point. * * This function is called when the module gets unloaded by Nagios. * It will deregister all previously registered callbacks and perform * some shutdown stuff. * * @param[in] flags XXX * @param[in] reason XXX * * @return 0 on success, any other value on failure. */ int nebmodule_deinit(int flags, int reason) { (void)flags; (void)reason; try { deregister_callbacks(); // Release allocated memory. deinit(); } // Avoid exception propagation in C code. catch (...) {} return (0); } /** * @brief Module entry point. * * This function is called when the module gets loaded by Nagios. It * will register callbacks to catch events and perform some * initialization stuff like config file parsing, thread creation, * ... * * @param[in] flags XXX * @param[in] args The argument string of the module (shall contain the * configuration file name). * @param[in] handle The module handle. * * @return 0 on success, any other value on failure. */ int nebmodule_init(int flags, char const* args, void* handle) { (void)flags; // Save module handle for future use. gl_mod_handle = handle; // Set module informations. neb_set_module_info(gl_mod_handle, NEBMODULE_MODINFO_TITLE, "CentreonBroker's cbmod"); neb_set_module_info(gl_mod_handle, NEBMODULE_MODINFO_AUTHOR, "Merethis"); neb_set_module_info(gl_mod_handle, NEBMODULE_MODINFO_COPYRIGHT, "Copyright 2009-2011 Merethis"); neb_set_module_info(gl_mod_handle, NEBMODULE_MODINFO_VERSION, "2.0.0"); neb_set_module_info(gl_mod_handle, NEBMODULE_MODINFO_LICENSE, "GPL version 2"); neb_set_module_info(gl_mod_handle, NEBMODULE_MODINFO_DESC, "cbmod is part of CentreonBroker and is designed to " \ "convert internal Nagios events to a proper data " \ "stream that can then be parsed by CentreonBroker's " \ "cb2db."); try { // Initialize necessary structures. init(); // Set configuration file. if (args) module::gl_configuration_file = args; // Try configuration parsing. config::parser p; config::state s; p.parse(module::gl_configuration_file, s); } catch (std::exception const& e) { logging::config << logging::HIGH << e.what(); return (-1); } catch (...) { logging::config << logging::HIGH << "configuration file parsing failed"; return (-1); } // Register callbacks. for (unsigned int i = 0; i < sizeof(gl_callbacks) / sizeof(*gl_callbacks); ++i) if (neb_register_callback(gl_callbacks[i].macro, gl_mod_handle, 0, gl_callbacks[i].callback) != NDO_OK) { deregister_callbacks(); return (-1); } else gl_callbacks[i].registered = true; return (0); } } <commit_msg>Fix NEB module that used init/deinit routines which are now removed.<commit_after>/* ** Copyright 2009-2011 MERETHIS ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. ** ** For more information: [email protected] */ #include <stddef.h> #include "config/parser.hh" #include "config/state.hh" #include "logging/logging.hh" #include "logging/syslogger.hh" #include "module/callbacks.hh" #include "module/internal.hh" #include "nagios/common.h" #include "nagios/nebcallbacks.h" using namespace com::centreon::broker; /************************************** * * * Global Objects * * * **************************************/ // Specify the event broker API version. NEB_API_VERSION(CURRENT_NEB_API_VERSION) // Configuration file name. QString module::gl_configuration_file; // List of host IDs. std::map<std::string, int> module::gl_hosts; // List of service IDs. std::map<std::pair<std::string, std::string>, std::pair<int, int> > module::gl_services; // Sender object. multiplexing::publisher module::gl_publisher; /************************************** * * * Static Objects * * * **************************************/ // List of callbacks static struct { unsigned int macro; int (* callback)(int, void*); bool registered; } gl_callbacks[] = { { NEBCALLBACK_ACKNOWLEDGEMENT_DATA, &module::callback_acknowledgement, false }, { NEBCALLBACK_COMMENT_DATA, &module::callback_comment, false }, { NEBCALLBACK_DOWNTIME_DATA, &module::callback_downtime, false }, { NEBCALLBACK_EVENT_HANDLER_DATA, &module::callback_event_handler, false }, { NEBCALLBACK_FLAPPING_DATA, &module::callback_flapping_status, false }, { NEBCALLBACK_HOST_CHECK_DATA, &module::callback_host_check, false }, { NEBCALLBACK_HOST_STATUS_DATA, &module::callback_host_status, false }, { NEBCALLBACK_LOG_DATA, &module::callback_log, false }, { NEBCALLBACK_PROCESS_DATA, &module::callback_process, false }, { NEBCALLBACK_PROGRAM_STATUS_DATA, &module::callback_program_status, false }, { NEBCALLBACK_SERVICE_CHECK_DATA, &module::callback_service_check, false }, { NEBCALLBACK_SERVICE_STATUS_DATA, &module::callback_service_status, false } }; // Module handle static void* gl_mod_handle = NULL; /************************************** * * * Static Functions * * * **************************************/ /** * @brief Deregister callbacks. * * Deregister all callbacks previously registered. */ static void deregister_callbacks() { for (unsigned int i = 0; i < sizeof(gl_callbacks) / sizeof(*gl_callbacks); ++i) if (gl_callbacks[i].registered) { neb_deregister_callback(gl_callbacks[i].macro, gl_callbacks[i].callback); gl_callbacks[i].registered = false; } return ; } /************************************** * * * Exported Functions * * * **************************************/ extern "C" { /** * @brief Module exit point. * * This function is called when the module gets unloaded by Nagios. * It will deregister all previously registered callbacks and perform * some shutdown stuff. * * @param[in] flags XXX * @param[in] reason XXX * * @return 0 on success, any other value on failure. */ int nebmodule_deinit(int flags, int reason) { (void)flags; (void)reason; try { deregister_callbacks(); } // Avoid exception propagation in C code. catch (...) {} return (0); } /** * @brief Module entry point. * * This function is called when the module gets loaded by Nagios. It * will register callbacks to catch events and perform some * initialization stuff like config file parsing, thread creation, * ... * * @param[in] flags XXX * @param[in] args The argument string of the module (shall contain the * configuration file name). * @param[in] handle The module handle. * * @return 0 on success, any other value on failure. */ int nebmodule_init(int flags, char const* args, void* handle) { (void)flags; // Save module handle for future use. gl_mod_handle = handle; // Set module informations. neb_set_module_info(gl_mod_handle, NEBMODULE_MODINFO_TITLE, "CentreonBroker's cbmod"); neb_set_module_info(gl_mod_handle, NEBMODULE_MODINFO_AUTHOR, "Merethis"); neb_set_module_info(gl_mod_handle, NEBMODULE_MODINFO_COPYRIGHT, "Copyright 2009-2011 Merethis"); neb_set_module_info(gl_mod_handle, NEBMODULE_MODINFO_VERSION, "2.0.0"); neb_set_module_info(gl_mod_handle, NEBMODULE_MODINFO_LICENSE, "GPL version 2"); neb_set_module_info(gl_mod_handle, NEBMODULE_MODINFO_DESC, "cbmod is part of CentreonBroker and is designed to " \ "convert internal Nagios events to a proper data " \ "stream that can then be parsed by CentreonBroker's " \ "cb2db."); try { // Set configuration file. if (args) module::gl_configuration_file = args; // Try configuration parsing. config::parser p; config::state s; p.parse(module::gl_configuration_file, s); } catch (std::exception const& e) { logging::config << logging::HIGH << e.what(); return (-1); } catch (...) { logging::config << logging::HIGH << "configuration file parsing failed"; return (-1); } // Register callbacks. for (unsigned int i = 0; i < sizeof(gl_callbacks) / sizeof(*gl_callbacks); ++i) if (neb_register_callback(gl_callbacks[i].macro, gl_mod_handle, 0, gl_callbacks[i].callback) != NDO_OK) { deregister_callbacks(); return (-1); } else gl_callbacks[i].registered = true; return (0); } } <|endoftext|>
<commit_before>/* * ===================================================================================== * * Filename: mp4duration.cc * * Description: MP4 duration parser - node.js c++ addon * * Version: 1.0 * Created: 2014/10/24 16时14分34秒 * Revision: none * Compiler: gcc * * Author: XadillaX (http://xcoder.in/), [email protected] * Organization: Touhou Gensokyo * * ===================================================================================== */ #include <node.h> #include <node_buffer.h> #include "parse.h" #include <stdio.h> #include <string.h> #include <nan.h> using namespace v8; using namespace node; NAN_METHOD(ParseViaBuffer) { NanScope(); if(args.Length() < 1) { return NanThrowError("Wrong number of arguments."); } Local<Value> arg = args[0]; if(!node::Buffer::HasInstance(arg)) { return NanThrowError("Bad argument!"); } size_t size = Buffer::Length(arg->ToObject()); char* pbuf = Buffer::Data(arg->ToObject()); char* pbuf_end = pbuf + size; // check is it mp4 if(pbuf_end - pbuf < 7) { return NanThrowError("File is too small."); } char sign[] = { 0x00, 0x00, 0x00, 0x14, 0x66, 0x74, 0x79, 0x70 }; for(int i = 0; i < 8; i++) { if(i == 3) continue; if(sign[i] != *(pbuf + i)) { return NanThrowError("Broken MP4 file."); } } double file_duration = 0.0f; try { file_duration = ParseDuration(pbuf, pbuf_end); } catch(...) { return NanThrowError("Broken file or this format is not supported."); } NanReturnValue(NanNew<Number>(file_duration)); } NAN_METHOD(ParseViaFile) { NanScope(); if(args.Length() < 1) { return NanThrowError("Wrong number of arguments."); } Local<Value> pre_filename = args[0]; if(!pre_filename->IsString()) { return NanThrowError("Filename should be a string."); } NanAsciiString afilename = NanAsciiString(args[0]); char* filename = *afilename; printf("filename: %s\n", filename); FILE* fp = fopen(filename, "rb"); if(NULL == fp) { char temp[32 + strlen(filename)]; sprintf(temp, "Can't open this file: %s.", filename); return NanThrowError(temp); } unsigned int filesize; fseek(fp, 0, SEEK_END); filesize = ftell(fp); fseek(fp, 0, SEEK_SET); char* filebuf = new char[filesize]; fread(filebuf, filesize, 1, fp); fclose(fp); const char* pbuf = filebuf; const char* pbuf_end = filebuf + filesize; // check is it mp4 if(pbuf_end - pbuf < 7) { return NanThrowError("File is too small."); } char sign[] = { 0x00, 0x00, 0x00, 0x14, 0x66, 0x74, 0x79, 0x70 }; for(int i = 0; i < 8; i++) { if(i == 3) continue; if(sign[i] != *(pbuf + i)) { return NanThrowError("Broken MP4 file."); } } double file_duration = 0.0f; try { file_duration = ParseDuration(pbuf, pbuf_end); } catch(...) { return NanThrowError("Broken file or this format is not supported."); } NanReturnValue(NanNew<Number>(file_duration)); } void InitAll(Handle<Object> exports) { exports->Set(NanNew<String>("parseByFilename"), NanNew<FunctionTemplate>(ParseViaFile)->GetFunction()); exports->Set(NanNew<String>("parseByBuffer"), NanNew<FunctionTemplate>(ParseViaBuffer)->GetFunction()); } NODE_MODULE(mp4duration, InitAll); <commit_msg>add something to debug<commit_after>/* * ===================================================================================== * * Filename: mp4duration.cc * * Description: MP4 duration parser - node.js c++ addon * * Version: 1.0 * Created: 2014/10/24 16时14分34秒 * Revision: none * Compiler: gcc * * Author: XadillaX (http://xcoder.in/), [email protected] * Organization: Touhou Gensokyo * * ===================================================================================== */ #include <node.h> #include <node_buffer.h> #include "parse.h" #include <stdio.h> #include <string.h> #include <nan.h> using namespace v8; using namespace node; NAN_METHOD(ParseViaBuffer) { NanScope(); if(args.Length() < 1) { return NanThrowError("Wrong number of arguments."); } Local<Value> arg = args[0]; if(!node::Buffer::HasInstance(arg)) { return NanThrowError("Bad argument!"); } size_t size = Buffer::Length(arg->ToObject()); char* pbuf = Buffer::Data(arg->ToObject()); char* pbuf_end = pbuf + size; // check is it mp4 if(pbuf_end - pbuf < 7) { return NanThrowError("File is too small."); } char sign[] = { 0x00, 0x00, 0x00, 0x14, 0x66, 0x74, 0x79, 0x70 }; for(int i = 0; i < 8; i++) { if(i == 3) continue; if(sign[i] != *(pbuf + i)) { return NanThrowError("Broken MP4 file."); } } double file_duration = 0.0f; try { file_duration = ParseDuration(pbuf, pbuf_end); } catch(...) { return NanThrowError("Broken file or this format is not supported."); } NanReturnValue(NanNew<Number>(file_duration)); } NAN_METHOD(ParseViaFile) { NanScope(); if(args.Length() < 1) { return NanThrowError("Wrong number of arguments."); } Local<Value> pre_filename = args[0]; if(!pre_filename->IsString()) { return NanThrowError("Filename should be a string."); } NanAsciiString afilename(args[0]); char* filename = *afilename; printf("filename: %s\n", filename); FILE* fp = fopen(filename, "rb"); if(NULL == fp) { char temp[32 + strlen(filename)]; sprintf(temp, "Can't open this file: %s.", filename); return NanThrowError(temp); } unsigned int filesize; fseek(fp, 0, SEEK_END); filesize = ftell(fp); fseek(fp, 0, SEEK_SET); char* filebuf = new char[filesize]; fread(filebuf, filesize, 1, fp); fclose(fp); const char* pbuf = filebuf; const char* pbuf_end = filebuf + filesize; // check is it mp4 if(pbuf_end - pbuf < 7) { return NanThrowError("File is too small."); } char sign[] = { 0x00, 0x00, 0x00, 0x14, 0x66, 0x74, 0x79, 0x70 }; for(int i = 0; i < 8; i++) { if(i == 3) continue; if(sign[i] != *(pbuf + i)) { return NanThrowError("Broken MP4 file."); } } double file_duration = 0.0f; try { file_duration = ParseDuration(pbuf, pbuf_end); } catch(...) { return NanThrowError("Broken file or this format is not supported."); } NanReturnValue(NanNew<Number>(file_duration)); } void InitAll(Handle<Object> exports) { exports->Set(NanNew<String>("parseByFilename"), NanNew<FunctionTemplate>(ParseViaFile)->GetFunction()); exports->Set(NanNew<String>("parseByBuffer"), NanNew<FunctionTemplate>(ParseViaBuffer)->GetFunction()); } NODE_MODULE(mp4duration, InitAll); <|endoftext|>
<commit_before>// Copyright 2014 J.C. Moyer // // 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 <StormLib.h> extern "C" { #include <lua.h> #include <lualib.h> #include <lauxlib.h> } #include "common.h" #include "file_handle.h" // name of the mpqhandle metatable const char* MPQHANDLE_UDNAME = "mpqhandle"; // converts a HANDLE to an mpqhandle userdata and pushes it onto the stack void moonstorm_newmpqhandle(lua_State* L, HANDLE h) { HANDLE* udhandle = static_cast<HANDLE*>(lua_newuserdata(L, sizeof(HANDLE))); *udhandle = h; luaL_setmetatable(L, MPQHANDLE_UDNAME); } // ensures that the value on top of the stack is a mpqhandle userdata HANDLE* moonstorm_checkmpqhandle(lua_State* L, int arg) { return static_cast<HANDLE*>(luaL_checkudata(L, arg, MPQHANDLE_UDNAME)); } // mpq:addlistfile(filename) int moonstorm_mpq_addlistfile(lua_State* L) { HANDLE* h = moonstorm_checkmpqhandle(L, 1); const char* filename = luaL_checkstring(L, 2); int result = SFileAddListFile(*h, filename); if (result == ERROR_SUCCESS) { lua_pushboolean(L, true); return 1; } else { lua_pushnil(L); lua_pushinteger(L, result); return 2; } } // mpq:openfile(filename [, search_scope=0]) int moonstorm_mpq_openfile(lua_State* L) { HANDLE* h = moonstorm_checkmpqhandle(L, 1); const char* filename = luaL_checkstring(L, 2); DWORD search_scope = luaL_optint(L, 3, 0); HANDLE file_handle; if (SFileOpenFileEx(*h, filename, search_scope, &file_handle)) { moonstorm_newfilehandle(L, file_handle); return 1; } else { return moonstorm_push_last_err(L); } } // mpq:create(filename, filesize, flags) int moonstorm_mpq_createfile(lua_State* L) { HANDLE* h = moonstorm_checkmpqhandle(L, 1); const char* filename = luaL_checkstring(L, 2); ULONGLONG filetime = 0; DWORD filesize = luaL_checkint(L, 3); LCID locale = 0; DWORD flags = luaL_checkint(L, 4); HANDLE file_handle; if (SFileCreateFile(*h, filename, filetime, filesize, locale, flags, &file_handle)) { moonstorm_newfilehandle(L, file_handle); return 1; } else { return moonstorm_push_last_err(L); } } // mpq:flush() int moonstorm_mpq_flush(lua_State* L) { HANDLE* h = moonstorm_checkmpqhandle(L, 1); if (!SFileFlushArchive(*h)) { return moonstorm_push_last_err(L); } return 0; } // mpq:close() int moonstorm_mpq_close(lua_State* L) { HANDLE* h = moonstorm_checkmpqhandle(L, 1); if (!SFileCloseArchive(*h)) { return moonstorm_push_last_err(L); } return 0; } // mpq:hasfile(filename) int moonstorm_mpq_hasfile(lua_State* L) { HANDLE* h = moonstorm_checkmpqhandle(L, 1); const char* filename = luaL_checkstring(L, 2); if (SFileHasFile(*h, filename)) { lua_pushboolean(L, true); } else if (GetLastError() == ERROR_FILE_NOT_FOUND) { lua_pushboolean(L, false); } else { return moonstorm_push_last_err(L); } return 1; } // docs say this takes LARGE_INTEGER* but source code says ULONGLONG void WINAPI moonstorm_mpq_compact_cb(void* userdata, DWORD worktype, ULONGLONG processed, ULONGLONG total) { lua_State* L = static_cast<lua_State*>(userdata); // dup function lua_pushvalue(L, -1); lua_pushinteger(L, worktype); lua_pushinteger(L, processed); lua_pushinteger(L, total); int result = lua_pcall(L, 3, 0, 0); if (result != LUA_OK) { // TODO: better way to handle errors instead of swallowing them? lua_pop(L, 1); } } // mpq:compact([listfile,] [callback]) int moonstorm_mpq_compact(lua_State* L) { HANDLE* h = moonstorm_checkmpqhandle(L, 1); const char* listfile = NULL; int func = 0; if (lua_isstring(L, 2)) { listfile = lua_tostring(L, 2); } else if (lua_isfunction(L, 2)) { func = 2; } // if #2 is a string, try #3 for a function if (func == 0 && listfile && lua_isfunction(L, 3)) { func = 3; } if (func > 0) { // func is already on top of the stack so we'll just take it from there in // the callback SFileSetCompactCallback(*h, moonstorm_mpq_compact_cb, static_cast<void*>(L)); } if (SFileCompactArchive(*h, listfile, false)) { return 0; } else { return moonstorm_push_last_err(L); } } static const struct luaL_Reg mpqhandle_lib[] = { {"addlistfile", moonstorm_mpq_addlistfile}, {"openfile", moonstorm_mpq_openfile}, {"createfile", moonstorm_mpq_createfile}, {"flush", moonstorm_mpq_flush}, {"close", moonstorm_mpq_close}, {"hasfile", moonstorm_mpq_hasfile}, {"compact", moonstorm_mpq_compact}, {NULL, NULL} }; void moonstorm_init_mpqhandle(lua_State* L) { // set up mt for mpqhandles luaL_newmetatable(L, MPQHANDLE_UDNAME); lua_newtable(L); luaL_setfuncs(L, mpqhandle_lib, 0); lua_setfield(L, -2, "__index"); lua_pop(L, 1); } <commit_msg>Support setting max file count on MPQs<commit_after>// Copyright 2014 J.C. Moyer // // 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 <StormLib.h> extern "C" { #include <lua.h> #include <lualib.h> #include <lauxlib.h> } #include "common.h" #include "file_handle.h" // name of the mpqhandle metatable const char* MPQHANDLE_UDNAME = "mpqhandle"; // converts a HANDLE to an mpqhandle userdata and pushes it onto the stack void moonstorm_newmpqhandle(lua_State* L, HANDLE h) { HANDLE* udhandle = static_cast<HANDLE*>(lua_newuserdata(L, sizeof(HANDLE))); *udhandle = h; luaL_setmetatable(L, MPQHANDLE_UDNAME); } // ensures that the value on top of the stack is a mpqhandle userdata HANDLE* moonstorm_checkmpqhandle(lua_State* L, int arg) { return static_cast<HANDLE*>(luaL_checkudata(L, arg, MPQHANDLE_UDNAME)); } // mpq:addlistfile(filename) int moonstorm_mpq_addlistfile(lua_State* L) { HANDLE* h = moonstorm_checkmpqhandle(L, 1); const char* filename = luaL_checkstring(L, 2); int result = SFileAddListFile(*h, filename); if (result == ERROR_SUCCESS) { lua_pushboolean(L, true); return 1; } else { lua_pushnil(L); lua_pushinteger(L, result); return 2; } } // mpq:openfile(filename [, search_scope=0]) int moonstorm_mpq_openfile(lua_State* L) { HANDLE* h = moonstorm_checkmpqhandle(L, 1); const char* filename = luaL_checkstring(L, 2); DWORD search_scope = luaL_optint(L, 3, 0); HANDLE file_handle; if (SFileOpenFileEx(*h, filename, search_scope, &file_handle)) { moonstorm_newfilehandle(L, file_handle); return 1; } else { return moonstorm_push_last_err(L); } } // mpq:create(filename, filesize, flags) int moonstorm_mpq_createfile(lua_State* L) { HANDLE* h = moonstorm_checkmpqhandle(L, 1); const char* filename = luaL_checkstring(L, 2); ULONGLONG filetime = 0; DWORD filesize = luaL_checkint(L, 3); LCID locale = 0; DWORD flags = luaL_checkint(L, 4); HANDLE file_handle; if (SFileCreateFile(*h, filename, filetime, filesize, locale, flags, &file_handle)) { moonstorm_newfilehandle(L, file_handle); return 1; } else { return moonstorm_push_last_err(L); } } // mpq:flush() int moonstorm_mpq_flush(lua_State* L) { HANDLE* h = moonstorm_checkmpqhandle(L, 1); if (!SFileFlushArchive(*h)) { return moonstorm_push_last_err(L); } return 0; } // mpq:close() int moonstorm_mpq_close(lua_State* L) { HANDLE* h = moonstorm_checkmpqhandle(L, 1); if (!SFileCloseArchive(*h)) { return moonstorm_push_last_err(L); } return 0; } // mpq:hasfile(filename) int moonstorm_mpq_hasfile(lua_State* L) { HANDLE* h = moonstorm_checkmpqhandle(L, 1); const char* filename = luaL_checkstring(L, 2); if (SFileHasFile(*h, filename)) { lua_pushboolean(L, true); } else if (GetLastError() == ERROR_FILE_NOT_FOUND) { lua_pushboolean(L, false); } else { return moonstorm_push_last_err(L); } return 1; } // mpq:setmaxfilecount(n) int moonstorm_mpq_setmaxfilecount(lua_State* L) { HANDLE* h = moonstorm_checkmpqhandle(L, 1); DWORD maxfilecount = luaL_checkint(L, 2); if (!SFileSetMaxFileCount(*h, maxfilecount)) { return moonstorm_push_last_err(L); } return 0; } // docs say this takes LARGE_INTEGER* but source code says ULONGLONG void WINAPI moonstorm_mpq_compact_cb(void* userdata, DWORD worktype, ULONGLONG processed, ULONGLONG total) { lua_State* L = static_cast<lua_State*>(userdata); // dup function lua_pushvalue(L, -1); lua_pushinteger(L, worktype); lua_pushinteger(L, processed); lua_pushinteger(L, total); int result = lua_pcall(L, 3, 0, 0); if (result != LUA_OK) { // TODO: better way to handle errors instead of swallowing them? lua_pop(L, 1); } } // mpq:compact([listfile,] [callback]) int moonstorm_mpq_compact(lua_State* L) { HANDLE* h = moonstorm_checkmpqhandle(L, 1); const char* listfile = NULL; int func = 0; if (lua_isstring(L, 2)) { listfile = lua_tostring(L, 2); } else if (lua_isfunction(L, 2)) { func = 2; } // if #2 is a string, try #3 for a function if (func == 0 && listfile && lua_isfunction(L, 3)) { func = 3; } if (func > 0) { // func is already on top of the stack so we'll just take it from there in // the callback SFileSetCompactCallback(*h, moonstorm_mpq_compact_cb, static_cast<void*>(L)); } if (SFileCompactArchive(*h, listfile, false)) { return 0; } else { return moonstorm_push_last_err(L); } } static const struct luaL_Reg mpqhandle_lib[] = { {"addlistfile", moonstorm_mpq_addlistfile}, {"openfile", moonstorm_mpq_openfile}, {"createfile", moonstorm_mpq_createfile}, {"flush", moonstorm_mpq_flush}, {"close", moonstorm_mpq_close}, {"hasfile", moonstorm_mpq_hasfile}, {"setmaxfilecount", moonstorm_mpq_setmaxfilecount}, {"compact", moonstorm_mpq_compact}, {NULL, NULL} }; void moonstorm_init_mpqhandle(lua_State* L) { // set up mt for mpqhandles luaL_newmetatable(L, MPQHANDLE_UDNAME); lua_newtable(L); luaL_setfuncs(L, mpqhandle_lib, 0); lua_setfield(L, -2, "__index"); lua_pop(L, 1); } <|endoftext|>
<commit_before>#include <allegro.h> #include <cstring> #include <iostream> #include <sstream> #include <stdlib.h> #include <pthread.h> #include <time.h> #include <vector> #include <map> #include "globals.h" #include "mugen_reader.h" #include "mugen_section.h" #include "mugen_item_content.h" #include "mugen_item.h" #include "mugen_character.h" #include "mugen_animation.h" #include "mugen_sprite.h" #include "util/bitmap.h" #include "util/funcs.h" #include "factory/font_render.h" #include "gui/keyinput_manager.h" using namespace std; static void showCollision( const std::vector< MugenArea > &vec, Bitmap &bmp, int x, int y, int w, int h, int color ){ for( unsigned int i = 0; i < vec.size(); ++i ){ bmp.rectangle( x + vec[i].x1, y + vec[i].y1, (x + w) + vec[i].x2, (y + h) + vec[i].y2, color ); } } static bool isArg( const char * s1, const char * s2 ){ return strcasecmp( s1, s2 ) == 0; } static void showOptions(){ Global::debug(0) << "M.U.G.E.N. Config Reader:" << endl; Global::debug(0) << "-f <file>: Load a M.U.G.E.N. config file and output to screen." << endl; Global::debug(0) << "-c <name>: Load a M.U.G.E.N. character and output some data about it.\n ie: 'data/mugen/chars/name' only pass name." << endl; Global::debug(0) << endl; } /* testing testing 1 2 3 */ void testPCX(){ unsigned char data[1 << 18]; FILE * f = fopen("x.pcx", "r"); int length; length = fread(data, sizeof(char), 1<<18, f); Global::debug(0) << "Size is " << length << endl; fclose(f); Bitmap b = Bitmap::memoryPCX(data, length); // Bitmap b("x.pcx"); if (b.getError()){ Global::debug(0) << "what the hell" << endl; } Bitmap work(640, 480); work.circleFill(40, 40, 100, Bitmap::makeColor(255, 0, 0)); b.draw(0, 0, work); Global::debug(0) << "Width " << b.getWidth() << " Height " << b.getHeight() << endl; work.BlitToScreen(); Util::rest(3000); } int main( int argc, char ** argv ){ if(argc <= 1){ showOptions(); return 0; } const char * FILE_ARG = "-f"; const char * LOC_ARG = "-c"; const char * DEBUG_ARG = "-l"; std::string ourFile; bool configLoaded = false; allegro_init(); install_timer(); install_keyboard(); set_color_depth(16); Bitmap::setGfxModeWindowed(640, 480); for ( int q = 1; q < argc; q++ ){ if ( isArg( argv[ q ], FILE_ARG ) ){ q += 1; if ( q < argc ){ ourFile = std::string( argv[ q ] ); configLoaded = !configLoaded; } else{ Global::debug(0) << "Error no file given!" << endl; showOptions(); return 0; } } else if ( isArg( argv[ q ], LOC_ARG ) ){ q += 1; if ( q < argc ){ ourFile = std::string( argv[ q ] ); } else{ Global::debug(0) << "Error no file given!" << endl; showOptions(); return 0; } } else if (isArg(argv[q], DEBUG_ARG)){ q += 1; if (q < argc){ istringstream i( argv[ q ] ); int f; i >> f; Global::setDebug( f ); } else { Global::debug(0) << "No number given for " << DEBUG_ARG << endl; } } else { // WHAT? showOptions(); return 0; } } if( configLoaded ){ MugenReader reader( ourFile ); std::vector< MugenSection * > collection; try{ collection = reader.getCollection(); Global::debug(0) << endl << "---------------------------------------------------------" << endl; for( unsigned int i = 0; i < collection.size(); ++i ){ Global::debug(0) << collection[i]->getHeader() << endl; Global::debug(0) << "---------------------------------------------------------" << endl; while( collection[i]->hasItems() ){ MugenItemContent *content = collection[i]->getNext(); while( content->hasItems() ){ Global::debug(0) << content->getNext()->query(); if( content->hasItems() ) Global::debug(0) << ","; } Global::debug(0) << endl; } Global::debug(0) << "---------------------------------------------------------" << endl; } Global::debug(0) << endl; } catch( MugenException &ex){ Global::debug(0) << "Problem loading file, error was: " << ex.getReason() << endl; return 1; } } else{ try{ Global::debug(0) << "Trying to load character: " << ourFile << "..." << endl; MugenCharacter character( ourFile ); character.load(); /* for (map<int,MugenAnimation*>::const_iterator it = character.getAnimations().begin(); it != character.getAnimations().end(); it++){ Global::debug(0) << "Animation " << it->first << endl; const vector<MugenFrame*> & frames = it->second->getFrames(); for (vector<MugenFrame*>::const_iterator frame = frames.begin(); frame != frames.end(); frame++){ MugenSprite * sprite = (*frame)->sprite; if (sprite == 0){ continue; } Bitmap b = new Bitmap(sffLoadPcxFromMemory( (char*) sprite->pcx ));;//Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength); b.BlitToScreen(); Util::rest(1000); } } */ Global::debug(0) << "Loaded character: \"" << character.getName() << "\" successfully." << endl; bool quit = false; bool animate = false; bool showClsn1 = false; bool showClsn2 = false; int ticks = 0; int loop = 0; map<int,MugenAnimation*>::const_iterator it = character.getAnimations().begin(); unsigned int currentAnim = 0; unsigned int lastAnim = character.getAnimations().size() -1; unsigned int currentFrame = 0; unsigned int lastFrame = it->second->getFrames().size() -1; MugenSprite * sprite = it->second->getFrames()[currentFrame]->sprite; Bitmap b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength); Bitmap work( 640, 480 ); while( !quit ){ work.clear(); keyInputManager::update(); ++ticks; // Since -1 is to stop the animation completely, we'll give it a pause of 150 ticks, because we want to see the loop const int time = it->second->getFrames()[currentFrame]->time == -1 ? 150 : it->second->getFrames()[currentFrame]->time; if(animate && ticks >= 15 + time){ ticks = 0; if( it->second->getFrames()[currentFrame]->loopstart ) loop = currentFrame; if( currentFrame < lastFrame )currentFrame++; else currentFrame = loop; sprite = it->second->getFrames()[currentFrame]->sprite; if (sprite != 0){ b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength); } } if( keyInputManager::keyState(keys::UP, true) ){ if( currentAnim < lastAnim ){ currentAnim++; it++; } loop = 0; currentFrame = 0; lastFrame = it->second->getFrames().size()-1; sprite = it->second->getFrames()[currentFrame]->sprite; if (sprite != 0){ b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength); } } else if( keyInputManager::keyState(keys::DOWN, true) ){ if( currentAnim > 0 ){ currentAnim--; it--; } loop = 0; currentFrame = 0; lastFrame = it->second->getFrames().size()-1; sprite = it->second->getFrames()[currentFrame]->sprite; if (sprite != 0){ b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength); } } else if( keyInputManager::keyState(keys::LEFT, true) && !animate){ if( currentFrame > 0 )currentFrame--; else currentFrame = lastFrame; sprite = it->second->getFrames()[currentFrame]->sprite; if (sprite != 0){ b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength); } } else if( keyInputManager::keyState(keys::RIGHT, true) && !animate){ if( currentFrame < lastFrame )currentFrame++; else currentFrame = 0; sprite = it->second->getFrames()[currentFrame]->sprite; if (sprite != 0){ b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength); } } else if( keyInputManager::keyState(keys::SPACE, true) ){ animate = !animate; } else if( keyInputManager::keyState('a', true) ){ showClsn1 = !showClsn1; } else if( keyInputManager::keyState('d', true) ){ showClsn2 = !showClsn2; } quit |= keyInputManager::keyState(keys::ESC, true ); b.draw(240 + it->second->getFrames()[currentFrame]->xoffset, 100 + it->second->getFrames()[currentFrame]->yoffset, work); if( showClsn2 )showCollision( it->second->getFrames()[currentFrame]->defenseCollision, work, 240, 100, b.getWidth(), b.getHeight(), Bitmap::makeColor( 0,255,0 ) ); if( showClsn1 )showCollision( it->second->getFrames()[currentFrame]->attackCollision, work, 240, 100, b.getWidth(), b.getHeight(), Bitmap::makeColor( 255,0,0 ) ); Font::getDefaultFont().printf( 15, 250, Bitmap::makeColor( 255, 255, 255 ), work, "Current Animation: %i, Current Frame: %i", 0, currentAnim, currentFrame ); if(sprite!=0)Font::getDefaultFont().printf( 15, 270, Bitmap::makeColor( 255, 255, 255 ), work, "Length: %d | x: %d | y: %d | Group: %d | Image: %d",0, sprite->length, sprite->x, sprite->y, sprite->groupNumber, sprite->imageNumber); Font::getDefaultFont().printf( 15, 280, Bitmap::makeColor( 255, 255, 255 ), work, "Bitmap info - Width: %i Height: %i",0, b.getWidth(), b.getHeight() ); Font::getDefaultFont().printf( 15, 290, Bitmap::makeColor( 255, 255, 255 ), work, "(space) Animation enabled: %i",0, animate ); Font::getDefaultFont().printf( 15, 300, Bitmap::makeColor( 255, 255, 255 ), work, "(d) Show Defense enabled (green): %i",0, showClsn2 ); Font::getDefaultFont().printf( 15, 310, Bitmap::makeColor( 255, 255, 255 ), work, "(a) Show Attack enabled (red): %i",0, showClsn1 ); work.BlitToScreen(); Util::rest(1); } } catch( MugenException &ex){ Global::debug(0) << "Problem loading file, error was: " << ex.getReason() << endl; return 1; } catch(...){ Global::debug(0) << "Unknown problem loading file" << endl; return 1; } } return 0; } <commit_msg>quit if no frames are available<commit_after>#include <allegro.h> #include <cstring> #include <iostream> #include <sstream> #include <stdlib.h> #include <pthread.h> #include <time.h> #include <vector> #include <map> #include "globals.h" #include "mugen_reader.h" #include "mugen_section.h" #include "mugen_item_content.h" #include "mugen_item.h" #include "mugen_character.h" #include "mugen_animation.h" #include "mugen_sprite.h" #include "util/bitmap.h" #include "util/funcs.h" #include "factory/font_render.h" #include "gui/keyinput_manager.h" using namespace std; static void showCollision( const std::vector< MugenArea > &vec, Bitmap &bmp, int x, int y, int w, int h, int color ){ for( unsigned int i = 0; i < vec.size(); ++i ){ bmp.rectangle( x + vec[i].x1, y + vec[i].y1, (x + w) + vec[i].x2, (y + h) + vec[i].y2, color ); } } static bool isArg( const char * s1, const char * s2 ){ return strcasecmp( s1, s2 ) == 0; } static void showOptions(){ Global::debug(0) << "M.U.G.E.N. Config Reader:" << endl; Global::debug(0) << "-f <file>: Load a M.U.G.E.N. config file and output to screen." << endl; Global::debug(0) << "-c <name>: Load a M.U.G.E.N. character and output some data about it.\n ie: 'data/mugen/chars/name' only pass name." << endl; Global::debug(0) << endl; } /* testing testing 1 2 3 */ void testPCX(){ unsigned char data[1 << 18]; FILE * f = fopen("x.pcx", "r"); int length; length = fread(data, sizeof(char), 1<<18, f); Global::debug(0) << "Size is " << length << endl; fclose(f); Bitmap b = Bitmap::memoryPCX(data, length); // Bitmap b("x.pcx"); if (b.getError()){ Global::debug(0) << "what the hell" << endl; } Bitmap work(640, 480); work.circleFill(40, 40, 100, Bitmap::makeColor(255, 0, 0)); b.draw(0, 0, work); Global::debug(0) << "Width " << b.getWidth() << " Height " << b.getHeight() << endl; work.BlitToScreen(); Util::rest(3000); } int main( int argc, char ** argv ){ if(argc <= 1){ showOptions(); return 0; } const char * FILE_ARG = "-f"; const char * LOC_ARG = "-c"; const char * DEBUG_ARG = "-l"; std::string ourFile; bool configLoaded = false; allegro_init(); install_timer(); install_keyboard(); set_color_depth(16); Bitmap::setGfxModeWindowed(640, 480); for ( int q = 1; q < argc; q++ ){ if ( isArg( argv[ q ], FILE_ARG ) ){ q += 1; if ( q < argc ){ ourFile = std::string( argv[ q ] ); configLoaded = !configLoaded; } else{ Global::debug(0) << "Error no file given!" << endl; showOptions(); return 0; } } else if ( isArg( argv[ q ], LOC_ARG ) ){ q += 1; if ( q < argc ){ ourFile = std::string( argv[ q ] ); } else{ Global::debug(0) << "Error no file given!" << endl; showOptions(); return 0; } } else if (isArg(argv[q], DEBUG_ARG)){ q += 1; if (q < argc){ istringstream i( argv[ q ] ); int f; i >> f; Global::setDebug( f ); } else { Global::debug(0) << "No number given for " << DEBUG_ARG << endl; } } else { // WHAT? showOptions(); return 0; } } if( configLoaded ){ MugenReader reader( ourFile ); std::vector< MugenSection * > collection; try{ collection = reader.getCollection(); Global::debug(0) << endl << "---------------------------------------------------------" << endl; for( unsigned int i = 0; i < collection.size(); ++i ){ Global::debug(0) << collection[i]->getHeader() << endl; Global::debug(0) << "---------------------------------------------------------" << endl; while( collection[i]->hasItems() ){ MugenItemContent *content = collection[i]->getNext(); while( content->hasItems() ){ Global::debug(0) << content->getNext()->query(); if( content->hasItems() ) Global::debug(0) << ","; } Global::debug(0) << endl; } Global::debug(0) << "---------------------------------------------------------" << endl; } Global::debug(0) << endl; } catch( MugenException &ex){ Global::debug(0) << "Problem loading file, error was: " << ex.getReason() << endl; return 1; } } else{ try{ Global::debug(0) << "Trying to load character: " << ourFile << "..." << endl; MugenCharacter character( ourFile ); character.load(); /* for (map<int,MugenAnimation*>::const_iterator it = character.getAnimations().begin(); it != character.getAnimations().end(); it++){ Global::debug(0) << "Animation " << it->first << endl; const vector<MugenFrame*> & frames = it->second->getFrames(); for (vector<MugenFrame*>::const_iterator frame = frames.begin(); frame != frames.end(); frame++){ MugenSprite * sprite = (*frame)->sprite; if (sprite == 0){ continue; } Bitmap b = new Bitmap(sffLoadPcxFromMemory( (char*) sprite->pcx ));;//Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength); b.BlitToScreen(); Util::rest(1000); } } */ Global::debug(0) << "Loaded character: \"" << character.getName() << "\" successfully." << endl; bool quit = false; bool animate = false; bool showClsn1 = false; bool showClsn2 = false; int ticks = 0; int loop = 0; map<int,MugenAnimation*>::const_iterator it = character.getAnimations().begin(); unsigned int currentAnim = 0; unsigned int lastAnim = character.getAnimations().size() -1; unsigned int currentFrame = 0; unsigned int lastFrame = it->second->getFrames().size() -1; if (it->second->getFrames().size() == 0){ Global::debug(0) << "No frames!" << endl; exit(0); } MugenSprite * sprite = it->second->getFrames()[currentFrame]->sprite; Bitmap b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength); Bitmap work( 640, 480 ); while( !quit ){ work.clear(); keyInputManager::update(); ++ticks; // Since -1 is to stop the animation completely, we'll give it a pause of 150 ticks, because we want to see the loop const int time = it->second->getFrames()[currentFrame]->time == -1 ? 150 : it->second->getFrames()[currentFrame]->time; if(animate && ticks >= 15 + time){ ticks = 0; if( it->second->getFrames()[currentFrame]->loopstart ) loop = currentFrame; if( currentFrame < lastFrame )currentFrame++; else currentFrame = loop; sprite = it->second->getFrames()[currentFrame]->sprite; if (sprite != 0){ b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength); } } if( keyInputManager::keyState(keys::UP, true) ){ if( currentAnim < lastAnim ){ currentAnim++; it++; } loop = 0; currentFrame = 0; lastFrame = it->second->getFrames().size()-1; sprite = it->second->getFrames()[currentFrame]->sprite; if (sprite != 0){ b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength); } } else if( keyInputManager::keyState(keys::DOWN, true) ){ if( currentAnim > 0 ){ currentAnim--; it--; } loop = 0; currentFrame = 0; lastFrame = it->second->getFrames().size()-1; sprite = it->second->getFrames()[currentFrame]->sprite; if (sprite != 0){ b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength); } } else if( keyInputManager::keyState(keys::LEFT, true) && !animate){ if( currentFrame > 0 )currentFrame--; else currentFrame = lastFrame; sprite = it->second->getFrames()[currentFrame]->sprite; if (sprite != 0){ b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength); } } else if( keyInputManager::keyState(keys::RIGHT, true) && !animate){ if( currentFrame < lastFrame )currentFrame++; else currentFrame = 0; sprite = it->second->getFrames()[currentFrame]->sprite; if (sprite != 0){ b = Bitmap::memoryPCX((unsigned char*) sprite->pcx, sprite->newlength); } } else if( keyInputManager::keyState(keys::SPACE, true) ){ animate = !animate; } else if( keyInputManager::keyState('a', true) ){ showClsn1 = !showClsn1; } else if( keyInputManager::keyState('d', true) ){ showClsn2 = !showClsn2; } quit |= keyInputManager::keyState(keys::ESC, true ); b.draw(240 + it->second->getFrames()[currentFrame]->xoffset, 100 + it->second->getFrames()[currentFrame]->yoffset, work); if( showClsn2 )showCollision( it->second->getFrames()[currentFrame]->defenseCollision, work, 240, 100, b.getWidth(), b.getHeight(), Bitmap::makeColor( 0,255,0 ) ); if( showClsn1 )showCollision( it->second->getFrames()[currentFrame]->attackCollision, work, 240, 100, b.getWidth(), b.getHeight(), Bitmap::makeColor( 255,0,0 ) ); Font::getDefaultFont().printf( 15, 250, Bitmap::makeColor( 255, 255, 255 ), work, "Current Animation: %i, Current Frame: %i", 0, currentAnim, currentFrame ); if(sprite!=0)Font::getDefaultFont().printf( 15, 270, Bitmap::makeColor( 255, 255, 255 ), work, "Length: %d | x: %d | y: %d | Group: %d | Image: %d",0, sprite->length, sprite->x, sprite->y, sprite->groupNumber, sprite->imageNumber); Font::getDefaultFont().printf( 15, 280, Bitmap::makeColor( 255, 255, 255 ), work, "Bitmap info - Width: %i Height: %i",0, b.getWidth(), b.getHeight() ); Font::getDefaultFont().printf( 15, 290, Bitmap::makeColor( 255, 255, 255 ), work, "(space) Animation enabled: %i",0, animate ); Font::getDefaultFont().printf( 15, 300, Bitmap::makeColor( 255, 255, 255 ), work, "(d) Show Defense enabled (green): %i",0, showClsn2 ); Font::getDefaultFont().printf( 15, 310, Bitmap::makeColor( 255, 255, 255 ), work, "(a) Show Attack enabled (red): %i",0, showClsn1 ); work.BlitToScreen(); Util::rest(1); } } catch( MugenException &ex){ Global::debug(0) << "Problem loading file, error was: " << ex.getReason() << endl; return 1; } catch(...){ Global::debug(0) << "Unknown problem loading file" << endl; return 1; } } return 0; } <|endoftext|>
<commit_before>/******************************************************************************* Copyright (c) 2014, Chris Vasseng 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 <organization> 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 IQUMULUS LLC 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. *******************************************************************************/ /* - data types determined by type of register. supported: * int16 [as, bs, cs, ds] * int32 [ii, ji, ki, li] * float [xf, yf, zf, wf] Test program: MOV as,#0 ;a = 0 MOV bs,#10 ;b = 10 LOOP: INC as ;a++ CMP as,bs JL LOOP ;if (a < b) goto LOOP => 0x0910 0x0000 //mov as,0 0x0920 0x000A //mov bs,10 0x1200 //LOOP: 0x0210 //inc as 0xE011 //cmp as,bs 0x1400 //jl loop */ //////////////////////////////////////////////////////////////////////////////// #define MAX_PROGRAM_SIZE 1024 #define MAX_SYMBOLS 256 #define PROGRAM_LOG 1 //If enabled, the VM will log everything it does to stdout #ifdef PROGRAM_LOG # define DEBUG_PLOG(x) printf x #else # define DEBUG_PLOG(x) do {} while (0) #endif #include <string.h> #include <stdio.h> #include "dvm.h" //Instructions supported by the VM enum Instruction { NOP = 0, //MATH OPERATIONS ADD, //1: Add something to a register INC, //2: Increase the value in a register SUB, //3: Subtract something from a register MUL, //4: Decrease the value in a register DEC, //5: Decrease the value in a register DIV, //6: Divide SIN, //7: Sin COS, //8: Cos //MISC MOV, //9: Move something into a register PUSH, //10: Push something to the stack POP, //11: Pop something off the stack ARG, //12: Push an argument onto the call stack CALL, //13: Call something CMP, //14: Compare two registers RET, //15: Return from a sub routine FN, //16: Function label DO, //17: Call a function label LBL, //18: A label (15) //JUMPS JMP, //19: Do a jump JL, //20: Jump if less than JG, //21: Jump if greater than JE, //22: Jump if equals JN, //23: Jump if not equals JLE, //24: Jump if less than or equal JGE, //25: Jump if greater than or equal }; //Describes a comparison result enum CompareResult { LESS, GREATER, LEQUAL, GEQAUL, EQUAL, NEQUAL }; //Register enum Operand { R_NONE = 0, //16-bit registers R_AS, //1 R_BS, //2 R_CS, //3 R_DS, //4 //32-bit registers R_II, //5 R_JI, //6 R_KI, //7 R_LI, //8 //Float registers R_XF, //9 R_YF, //10 R_ZF, //11 R_WF, //12 R_SH, //13: Short constant follows R_FL, //14: Float constant follows R_IN, //15: Int constant follows }; //Contains the current state of a VM typedef struct VM { //int16 registers short int16Reg[4]; //as, bs, cs, ds //int registers int int32Reg[4]; //ii, ji, ki, li //float registers float floatReg[4]; //xf, yf, zf, wf //Our symbols short symbols[MAX_SYMBOLS]; //The program we're currently running short program[MAX_PROGRAM_SIZE]; //The program cursor - our position within the program array int programCursor; //The size of the program in memory int programSize; //Stores the result of the last compare preformed CompareResult lastCmp; //The cursor before a jump int beforeCursor; } VM; //////////////////////////////////////////////////////////////////////////////// //Read two bytes from the program and return it inline short vm_read2b(VM &v) { return v.program[++v.programCursor]; } //Read four bytes from the program and return it inline int vm_read4b(VM &v) { return v.program[++v.programCursor] << 8 | v.program[++v.programCursor]; } //Get the value of an operand relative to current program cursor inline float vm_getOperandValue(Operand opa, VM &v) { if (opa > 0) { if (opa < 5) { return v.int16Reg[opa]; } else if (opa < 9) { return v.int32Reg[opa]; } else if (opa < 13) { return v.floatReg[opa]; } else if (opa == 13) { //Read 2 bytes return vm_read2b(v); } else { //Read 4 bytes return vm_read4b(v); } } return -1.1337f; } //Write to a register inline void regw(Operand opa, VM &v, float val) { if (opa > 0) { if (opa < 5) { v.int16Reg[opa] = val; } else if (opa < 9) { v.int32Reg[opa] = val; } else if (opa < 13) { v.floatReg[opa] = val; } } } //Preform a jump in the program. This is repeated quite a lot, so it's //refactored into a separate function to avoid too much code repetition. inline void jmp(int where, VM &v) { if (v.symbols[where] < v.programSize) { v.beforeCursor = v.programCursor; v.programCursor = v.symbols[where]; DEBUG_PLOG(("Jumped to %i\n", v.programCursor)); } } //////////////////////////////////////////////////////////////////////////////// //Prepare a VM void dvm_vm_clear(VM &v) { v.programSize = 0; v.programCursor = 0; } //Reset the program within a vm void dvm_vm_reset(VM &v) { v.programCursor = 0; } //Run the program in a vm void dvm_run(VM &v) { Instruction ins; Operand opa; Operand opb; float lValue; float rValue; short c; char lbyte; //We first need to do a pre-pass to gather all the symbols in the program. int cursor = 0; while (cursor < v.programSize) { ins = Instruction((v.program[cursor] & 0xFF00) >> 8); if (ins == LBL || ins == FN) { v.symbols[v.program[cursor] & 0x00FF] = cursor; } cursor++; } //Start our actual pass (or resume where we left of) while (v.programCursor < v.programSize) { c = v.program[v.programCursor]; ins = Instruction((c & 0xFF00) >> 8); //The instruction opa = Operand((c & 0x00F0) >> 4); //Left side operand opb = Operand( c & 0x000F); //Right side operand lbyte = c & 0x00FF; //Symbol lValue = vm_getOperandValue(opa, v); rValue = vm_getOperandValue(opb, v); switch (ins) { //Moves the right value into a register. case MOV: if (opa > 0 && opa < 13) { regw(opa, v, rValue); DEBUG_PLOG(("MOV %f into register %i\n", rValue, opa)); } break; //Increments the value in a register case INC: if (opa > 0 && opa < 13) { regw(opa, v, ++lValue); DEBUG_PLOG(("INC register %i\n", opa)); } break; //Compare two registers or values case CMP: if (lValue > rValue) v.lastCmp = GREATER; else if (lValue < rValue) v.lastCmp = LESS; else if (lValue == rValue) v.lastCmp = EQUAL; else v.lastCmp = NEQUAL; DEBUG_PLOG(("CMP %f with %f\n", lValue, rValue)); break; //Jump if less than case JL: if (v.lastCmp == LESS) jmp(lbyte, v); break; //Jump if greater than case JG: if (v.lastCmp == GREATER) jmp(lbyte, v); break; //Jump if equals case JE: if (v.lastCmp == EQUAL) jmp(lbyte, v); break; //Jump if not equals case JN: if (v.lastCmp != EQUAL) jmp(lbyte, v); break; //Jump if less than or equal case JLE: if (v.lastCmp == EQUAL || v.lastCmp == LESS) jmp(lbyte, v); break; //Jump if greater than or equal case JGE: if (v.lastCmp == EQUAL || v.lastCmp == GREATER) jmp(lbyte, v); break; //Do a jump case JMP: jmp(lbyte, v); break; default: break; }; ++v.programCursor; } } void dvm_run(const short *prog, unsigned int size) { VM v; dvm_vm_clear(v); v.programSize = size; memcpy(&v.program, prog, sizeof(short) * size); dvm_run(v); } <commit_msg>More instructions, callstack, fixes<commit_after>/******************************************************************************* Copyright (c) 2014, Chris Vasseng 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 <organization> 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 IQUMULUS LLC 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. *******************************************************************************/ /* Test program: MOV as,#0 ;a = 0 MOV bs,#10 ;b = 10 LOOP: INC as ;a++ CMP as,bs JL LOOP ;if (a < b) goto LOOP => 0x0910 0x0000 //mov as,0 0x0920 0x000A //mov bs,10 0x1200 //LOOP: 0x0210 //inc as 0xE012 //cmp as,bs 0x1400 //jl loop */ //////////////////////////////////////////////////////////////////////////////// #define MAX_PROGRAM_SIZE 1024 #define MAX_SYMBOLS 256 #define MAX_STACK_SIZE 64 #define MAX_CALLSTACK 1024 #define PROGRAM_LOG 1 //If enabled, the VM will log everything it does to stdout #ifdef PROGRAM_LOG # define DEBUG_PLOG(x) printf x #else # define DEBUG_PLOG(x) do {} while (0) #endif #include <string.h> #include <stdio.h> #include "dvm.h" #include "types.h" //////////////////////////////////////////////////////////////////////////////// //Describes a comparison result enum CompareResult { LESS, GREATER, LEQUAL, GEQAUL, EQUAL, NEQUAL }; //Contains the current state of a VM typedef struct VM { //int16 registers short int16Reg[4]; //as, bs, cs, ds //int registers int int32Reg[4]; //ii, ji, ki, li //float registers float floatReg[4]; //xf, yf, zf, wf //Our symbols short symbols[MAX_SYMBOLS]; //Our stack double stack[MAX_STACK_SIZE]; //Stack pointer int stackPointer; //The program we're currently running short program[MAX_PROGRAM_SIZE]; //The program cursor - our position within the program array int programCursor; //The size of the program in memory int programSize; //Stores the result of the last compare preformed CompareResult lastCmp; //The cursor before a jump *REPLACE WITH CALLSTACK* int beforeCursor; //Callstack int callstack[MAX_CALLSTACK]; int callstackPointer; } VM; //////////////////////////////////////////////////////////////////////////////// //The following are utility functions to make things a bit more tidy //Read two bytes from the program and return it inline short vm_read2b(VM &v) { return v.program[++v.programCursor]; } //Read four bytes from the program and return it inline int vm_read4b(VM &v) { return v.program[++v.programCursor] << 8 | v.program[++v.programCursor]; } //Get the value of an operand relative to current program cursor inline float vm_getOperandValue(Operand opa, VM &v) { if (opa > 0) { if (opa < 5) { return v.int16Reg[opa]; } else if (opa < 9) { return v.int32Reg[opa]; } else if (opa < 13) { return v.floatReg[opa]; } else if (opa == 13) { //Read 2 bytes return vm_read2b(v); } else { //Read 4 bytes return vm_read4b(v); } } return -1.1337f; } //Write to a register inline void regw(Operand opa, VM &v, float val) { if (opa > 0) { if (opa < 5) { v.int16Reg[opa] = val; } else if (opa < 9) { v.int32Reg[opa] = val; } else if (opa < 13) { v.floatReg[opa] = val; } } } //Preform a jump in the program. This is repeated quite a lot, so it's //refactored into a separate function to avoid too much code repetition. inline void jmp(int where, VM &v) { if (v.symbols[where] < v.programSize) { // v.beforeCursor = v.programCursor; //Add the jump to the call stack // v.callstack[v.callstackPointer] = v.programCursor; // v.callstackPointer++; v.programCursor = v.symbols[where]; DEBUG_PLOG(("Jumped to %i\n", v.programCursor)); } } //////////////////////////////////////////////////////////////////////////////// //Reset the program within a vm void dvm_vm_reset(VM &v) { v.programCursor = 0; v.stackPointer = 0; v.callstackPointer = 0; } //Prepare a VM void dvm_vm_clear(VM &v) { v.programSize = 0; dvm_vm_reset(v); } //Run the program in a vm void dvm_run(VM &v) { Instruction ins; Operand opa; Operand opb; float lValue; float rValue; short c; char lbyte; //We first need to do a pre-pass to gather all the symbols in the program. int cursor = 0; while (cursor < v.programSize) { ins = Instruction((v.program[cursor] & 0xFF00) >> 8); if (ins == LBL || ins == FN) { v.symbols[v.program[cursor] & 0x00FF] = cursor; } cursor++; } //Start our actual pass (or resume where we left of) while (v.programCursor < v.programSize) { c = v.program[v.programCursor]; ins = Instruction((c & 0xFF00) >> 8); //The instruction opa = Operand((c & 0x00F0) >> 4); //Left side operand opb = Operand( c & 0x000F); //Right side operand lbyte = c & 0x00FF; //Symbol lValue = vm_getOperandValue(opa, v); rValue = vm_getOperandValue(opb, v); switch (ins) { //Moves the right value into a register. case MOV: if (opa > 0 && opa < 13) { regw(opa, v, rValue); DEBUG_PLOG(("MOV %f into register %i\n", rValue, opa)); } break; //Increments the value in a register case INC: if (opa > 0 && opa < 13) { regw(opa, v, ++lValue); DEBUG_PLOG(("INC register %i\n", opa)); } break; //Compare two registers or values case CMP: if (lValue > rValue) v.lastCmp = GREATER; else if (lValue < rValue) v.lastCmp = LESS; else if (lValue == rValue) v.lastCmp = EQUAL; else v.lastCmp = NEQUAL; DEBUG_PLOG(("CMP %f with %f\n", lValue, rValue)); break; //Push a register or a value onto the stack case PUSH: if (opa > 0) { v.stack[v.stackPointer] = lValue; v.stackPointer++; DEBUG_PLOG(("PUSH %f onto stack\n", lValue)); } break; //Pop the top item of the stack and put it in a register case POP: if (v.stackPointer > 0 && opa > 0 && opa < 13) { v.stackPointer--; regw(opa, v, v.stack[v.stackPointer]); DEBUG_PLOG(("POP into %i\n", opa)); } break; //Return from a jump or function call case RET: if (v.callstackPointer > 0) { v.callstackPointer--; v.programCursor = v.callstack[v.callstackPointer]; DEBUG_PLOG(("RETURNED to %i\n", v.programCursor)); } break; case DO: if (v.symbols[lbyte] < v.programSize) { //Add the jump to the call stack v.callstack[v.callstackPointer] = v.programCursor; v.callstackPointer++; v.programCursor = v.symbols[lbyte]; DEBUG_PLOG(("Doing subroutine at %i\n", v.programCursor)); } break; ////////////////////////////////////////////////////////////////////////// //Here come the jumps //Jump if less than case JL: if (v.lastCmp == LESS) jmp(lbyte, v); break; //Jump if greater than case JG: if (v.lastCmp == GREATER) jmp(lbyte, v); break; //Jump if equals case JE: if (v.lastCmp == EQUAL) jmp(lbyte, v); break; //Jump if not equals case JN: if (v.lastCmp != EQUAL) jmp(lbyte, v); break; //Jump if less than or equal case JLE: if (v.lastCmp == EQUAL || v.lastCmp == LESS) jmp(lbyte, v); break; //Jump if greater than or equal case JGE: if (v.lastCmp == EQUAL || v.lastCmp == GREATER) jmp(lbyte, v); break; //Do a jump case JMP: jmp(lbyte, v); break; default: break; }; ++v.programCursor; } } void dvm_run(const short *prog, unsigned int size) { VM v; dvm_vm_clear(v); v.programSize = size; memcpy(&v.program, prog, sizeof(short) * size); dvm_run(v); } <|endoftext|>
<commit_before>#include "MS5837.h" #include <Wire.h> #define MS5837_ADDR 0x76 #define MS5837_RESET 0x1E #define MS5837_ADC_READ 0x00 #define MS5837_PROM_READ 0xA0 #define MS5837_CONVERT_D1_8192 0x4A #define MS5837_CONVERT_D2_8192 0x5A const float MS5837::Pa = 100.0f; const float MS5837::bar = 0.001f; const float MS5837::mbar = 1.0f; const uint8_t MS5837::MS5837_30BA = 0; const uint8_t MS5837::MS5837_02BA = 1; MS5837::MS5837() { fluidDensity = 1029; } bool MS5837::init() { // Reset the MS5837, per datasheet Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_RESET); Wire.endTransmission(); // Wait for reset to complete delay(10); // Read calibration values and CRC for ( uint8_t i = 0 ; i < 7 ; i++ ) { Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_PROM_READ+i*2); Wire.endTransmission(); Wire.requestFrom(MS5837_ADDR,2); C[i] = (Wire.read() << 8) | Wire.read(); } // Verify that data is correct with CRC uint8_t crcRead = C[0] >> 12; uint8_t crcCalculated = crc4(C); if ( crcCalculated == crcRead ) { return true; // Initialization success } return false; // CRC fail } void MS5837::setModel(uint8_t model) { _model = model; } void MS5837::setFluidDensity(float density) { fluidDensity = density; } void MS5837::read() { // Request D1 conversion Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_CONVERT_D1_8192); Wire.endTransmission(); delay(20); // Max conversion time per datasheet Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_ADC_READ); Wire.endTransmission(); Wire.requestFrom(MS5837_ADDR,3); D1 = 0; D1 = Wire.read(); D1 = (D1 << 8) | Wire.read(); D1 = (D1 << 8) | Wire.read(); // Request D2 conversion Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_CONVERT_D2_8192); Wire.endTransmission(); delay(20); // Max conversion time per datasheet Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_ADC_READ); Wire.endTransmission(); Wire.requestFrom(MS5837_ADDR,3); D2 = 0; D2 = Wire.read(); D2 = (D2 << 8) | Wire.read(); D2 = (D2 << 8) | Wire.read(); calculate(); } void MS5837::calculate() { // Given C1-C6 and D1, D2, calculated TEMP and P // Do conversion first and then second order temp compensation int32_t dT = 0; int64_t SENS = 0; int64_t OFF = 0; int32_t SENSi = 0; int32_t OFFi = 0; int32_t Ti = 0; int64_t OFF2 = 0; int64_t SENS2 = 0; // Terms called dT = D2-uint32_t(C[5])*256l; if ( _model == MS5837_02BA ) { SENS = int64_t(C[1])*65536l+(int64_t(C[3])*dT)/128l; OFF = int64_t(C[2])*131072l+(int64_t(C[4])*dT)/64l; P = (D1*SENS/(2097152l)-OFF)/(32768l); } else { SENS = int64_t(C[1])*32768l+(int64_t(C[3])*dT)/256l; OFF = int64_t(C[2])*65536l+(int64_t(C[4])*dT)/128l; P = (D1*SENS/(2097152l)-OFF)/(8192l); } // Temp conversion TEMP = 2000l+int64_t(dT)*C[6]/8388608LL; //Second order compensation if ( _model == MS5837_02BA ) { if((TEMP/100)<20){ //Low temp Ti = (11*int64_t(dT)*int64_t(dT))/(34359738368LL); OFFi = (31*(TEMP-2000)*(TEMP-2000))/8; SENSi = (63*(TEMP-2000)*(TEMP-2000))/32; } } else { if((TEMP/100)<20){ //Low temp Ti = (3*int64_t(dT)*int64_t(dT))/(8589934592LL); OFFi = (3*(TEMP-2000)*(TEMP-2000))/2; SENSi = (5*(TEMP-2000)*(TEMP-2000))/8; if((TEMP/100)<-15){ //Very low temp OFFi = OFFi+7*(TEMP+1500l)*(TEMP+1500l); SENSi = SENSi+4*(TEMP+1500l)*(TEMP+1500l); } } else if((TEMP/100)>=20){ //High temp Ti = 2*(dT*dT)/(137438953472LL); OFFi = (1*(TEMP-2000)*(TEMP-2000))/16; SENSi = 0; } } OFF2 = OFF-OFFi; //Calculate pressure and temp second order SENS2 = SENS-SENSi; if ( _model == MS5837_02BA ) { TEMP = (TEMP-Ti); P = (((D1*SENS2)/2097152l-OFF2)/32768l)/100; } else { TEMP = (TEMP-Ti); P = (((D1*SENS2)/2097152l-OFF2)/8192l)/10; } } float MS5837::pressure(float conversion) { return P*conversion; } float MS5837::temperature() { return TEMP/100.0f; } float MS5837::depth() { return (pressure(MS5837::Pa)-101300)/(fluidDensity*9.80665); } float MS5837::altitude() { return (1-pow((pressure()/1013.25),.190284))*145366.45*.3048; } uint8_t MS5837::crc4(uint16_t n_prom[]) { uint16_t n_rem = 0; n_prom[0] = ((n_prom[0]) & 0x0FFF); n_prom[7] = 0; for ( uint8_t i = 0 ; i < 16; i++ ) { if ( i%2 == 1 ) { n_rem ^= (uint16_t)((n_prom[i>>1]) & 0x00FF); } else { n_rem ^= (uint16_t)(n_prom[i>>1] >> 8); } for ( uint8_t n_bit = 8 ; n_bit > 0 ; n_bit-- ) { if ( n_rem & 0x8000 ) { n_rem = (n_rem << 1) ^ 0x3000; } else { n_rem = (n_rem << 1); } } } n_rem = ((n_rem >> 12) & 0x000F); return n_rem ^ 0x00; } <commit_msg>changed pressure calculation to floating point division to allow for full resolution of MS5837 sensor<commit_after>#include "MS5837.h" #include <Wire.h> #define MS5837_ADDR 0x76 #define MS5837_RESET 0x1E #define MS5837_ADC_READ 0x00 #define MS5837_PROM_READ 0xA0 #define MS5837_CONVERT_D1_8192 0x4A #define MS5837_CONVERT_D2_8192 0x5A const float MS5837::Pa = 100.0f; const float MS5837::bar = 0.001f; const float MS5837::mbar = 1.0f; const uint8_t MS5837::MS5837_30BA = 0; const uint8_t MS5837::MS5837_02BA = 1; MS5837::MS5837() { fluidDensity = 1029; } bool MS5837::init() { // Reset the MS5837, per datasheet Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_RESET); Wire.endTransmission(); // Wait for reset to complete delay(10); // Read calibration values and CRC for ( uint8_t i = 0 ; i < 7 ; i++ ) { Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_PROM_READ+i*2); Wire.endTransmission(); Wire.requestFrom(MS5837_ADDR,2); C[i] = (Wire.read() << 8) | Wire.read(); } // Verify that data is correct with CRC uint8_t crcRead = C[0] >> 12; uint8_t crcCalculated = crc4(C); if ( crcCalculated == crcRead ) { return true; // Initialization success } return false; // CRC fail } void MS5837::setModel(uint8_t model) { _model = model; } void MS5837::setFluidDensity(float density) { fluidDensity = density; } void MS5837::read() { // Request D1 conversion Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_CONVERT_D1_8192); Wire.endTransmission(); delay(20); // Max conversion time per datasheet Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_ADC_READ); Wire.endTransmission(); Wire.requestFrom(MS5837_ADDR,3); D1 = 0; D1 = Wire.read(); D1 = (D1 << 8) | Wire.read(); D1 = (D1 << 8) | Wire.read(); // Request D2 conversion Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_CONVERT_D2_8192); Wire.endTransmission(); delay(20); // Max conversion time per datasheet Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_ADC_READ); Wire.endTransmission(); Wire.requestFrom(MS5837_ADDR,3); D2 = 0; D2 = Wire.read(); D2 = (D2 << 8) | Wire.read(); D2 = (D2 << 8) | Wire.read(); calculate(); } void MS5837::calculate() { // Given C1-C6 and D1, D2, calculated TEMP and P // Do conversion first and then second order temp compensation int32_t dT = 0; int64_t SENS = 0; int64_t OFF = 0; int32_t SENSi = 0; int32_t OFFi = 0; int32_t Ti = 0; int64_t OFF2 = 0; int64_t SENS2 = 0; // Terms called dT = D2-uint32_t(C[5])*256l; if ( _model == MS5837_02BA ) { SENS = int64_t(C[1])*65536l+(int64_t(C[3])*dT)/128l; OFF = int64_t(C[2])*131072l+(int64_t(C[4])*dT)/64l; P = (D1*SENS/(2097152l)-OFF)/(32768l); } else { SENS = int64_t(C[1])*32768l+(int64_t(C[3])*dT)/256l; OFF = int64_t(C[2])*65536l+(int64_t(C[4])*dT)/128l; P = (D1*SENS/(2097152l)-OFF)/(8192l); } // Temp conversion TEMP = 2000l+int64_t(dT)*C[6]/8388608LL; //Second order compensation if ( _model == MS5837_02BA ) { if((TEMP/100)<20){ //Low temp Ti = (11*int64_t(dT)*int64_t(dT))/(34359738368LL); OFFi = (31*(TEMP-2000)*(TEMP-2000))/8; SENSi = (63*(TEMP-2000)*(TEMP-2000))/32; } } else { if((TEMP/100)<20){ //Low temp Ti = (3*int64_t(dT)*int64_t(dT))/(8589934592LL); OFFi = (3*(TEMP-2000)*(TEMP-2000))/2; SENSi = (5*(TEMP-2000)*(TEMP-2000))/8; if((TEMP/100)<-15){ //Very low temp OFFi = OFFi+7*(TEMP+1500l)*(TEMP+1500l); SENSi = SENSi+4*(TEMP+1500l)*(TEMP+1500l); } } else if((TEMP/100)>=20){ //High temp Ti = 2*(dT*dT)/(137438953472LL); OFFi = (1*(TEMP-2000)*(TEMP-2000))/16; SENSi = 0; } } OFF2 = OFF-OFFi; //Calculate pressure and temp second order SENS2 = SENS-SENSi; TEMP = (TEMP-Ti); if ( _model == MS5837_02BA ) { P = (((D1*SENS2)/2097152l-OFF2)/32768l); } else { P = (((D1*SENS2)/2097152l-OFF2)/8192l); } } float MS5837::pressure(float conversion) { if ( _model == MS5837_02BA ) { return P*conversion/100.0f; } else { return P*conversion/10.0f; } } float MS5837::temperature() { return TEMP/100.0f; } float MS5837::depth() { return (pressure(MS5837::Pa)-101300)/(fluidDensity*9.80665); } float MS5837::altitude() { return (1-pow((pressure()/1013.25),.190284))*145366.45*.3048; } uint8_t MS5837::crc4(uint16_t n_prom[]) { uint16_t n_rem = 0; n_prom[0] = ((n_prom[0]) & 0x0FFF); n_prom[7] = 0; for ( uint8_t i = 0 ; i < 16; i++ ) { if ( i%2 == 1 ) { n_rem ^= (uint16_t)((n_prom[i>>1]) & 0x00FF); } else { n_rem ^= (uint16_t)(n_prom[i>>1] >> 8); } for ( uint8_t n_bit = 8 ; n_bit > 0 ; n_bit-- ) { if ( n_rem & 0x8000 ) { n_rem = (n_rem << 1) ^ 0x3000; } else { n_rem = (n_rem << 1); } } } n_rem = ((n_rem >> 12) & 0x000F); return n_rem ^ 0x00; } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gdef.h" #include <limits> #include <vector> #include "gpos.h" #include "gsub.h" #include "layout.h" #include "maxp.h" // GDEF - The Glyph Definition Table // http://www.microsoft.com/typography/otspec/gdef.htm namespace { // The maximum class value in class definition tables. const uint16_t kMaxClassDefValue = 0xFFFF; // The maximum class value in the glyph class definision table. const uint16_t kMaxGlyphClassDefValue = 4; // The maximum format number of caret value tables. // We don't support format 3 for now. See the comment in // ParseLigCaretListTable() for the reason. const uint16_t kMaxCaretValueFormat = 2; bool ParseGlyphClassDefTable(ots::OpenTypeFile *file, const uint8_t *data, size_t length, const uint16_t num_glyphs) { return ots::ParseClassDefTable(data, length, num_glyphs, kMaxGlyphClassDefValue); } bool ParseAttachListTable(ots::OpenTypeFile *file, const uint8_t *data, size_t length, const uint16_t num_glyphs) { ots::Buffer subtable(data, length); uint16_t offset_coverage = 0; uint16_t glyph_count = 0; if (!subtable.ReadU16(&offset_coverage) || !subtable.ReadU16(&glyph_count)) { return OTS_FAILURE(); } const unsigned attach_points_end = static_cast<unsigned>(4) + 2*glyph_count; if (attach_points_end > std::numeric_limits<uint16_t>::max()) { return OTS_FAILURE(); } if (offset_coverage == 0 || offset_coverage >= length || offset_coverage < attach_points_end) { return OTS_FAILURE(); } if (glyph_count > num_glyphs) { OTS_WARNING("bad glyph count: %u", glyph_count); return OTS_FAILURE(); } std::vector<uint16_t> attach_points; attach_points.resize(glyph_count); for (unsigned i = 0; i < glyph_count; ++i) { if (!subtable.ReadU16(&attach_points[i])) { return OTS_FAILURE(); } if (attach_points[i] >= length || attach_points[i] < attach_points_end) { return OTS_FAILURE(); } } // Parse coverage table if (!ots::ParseCoverageTable(data + offset_coverage, length - offset_coverage, num_glyphs)) { return OTS_FAILURE(); } // Parse attach point table for (unsigned i = 0; i < attach_points.size(); ++i) { subtable.set_offset(attach_points[i]); uint16_t point_count = 0; if (!subtable.ReadU16(&point_count)) { return OTS_FAILURE(); } if (point_count == 0) { return OTS_FAILURE(); } uint16_t last_point_index = 0; uint16_t point_index = 0; for (unsigned j = 0; j < point_count; ++j) { if (!subtable.ReadU16(&point_index)) { return OTS_FAILURE(); } // Contour point indeces are in increasing numerical order if (last_point_index != 0 && last_point_index >= point_index) { OTS_WARNING("bad contour indeces: %u >= %u", last_point_index, point_index); return OTS_FAILURE(); } last_point_index = point_index; } } return true; } bool ParseLigCaretListTable(ots::OpenTypeFile *file, const uint8_t *data, size_t length, const uint16_t num_glyphs) { ots::Buffer subtable(data, length); uint16_t offset_coverage = 0; uint16_t lig_glyph_count = 0; if (!subtable.ReadU16(&offset_coverage) || !subtable.ReadU16(&lig_glyph_count)) { return OTS_FAILURE(); } const unsigned lig_glyphs_end = static_cast<unsigned>(4) + 2*lig_glyph_count; if (lig_glyphs_end > std::numeric_limits<uint16_t>::max()) { return OTS_FAILURE(); } if (offset_coverage == 0 || offset_coverage >= length || offset_coverage < lig_glyphs_end) { return OTS_FAILURE(); } if (lig_glyph_count > num_glyphs) { OTS_WARNING("bad ligature glyph count: %u", lig_glyph_count); return OTS_FAILURE(); } std::vector<uint16_t> lig_glyphs; lig_glyphs.resize(lig_glyph_count); for (unsigned i = 0; i < lig_glyph_count; ++i) { if (!subtable.ReadU16(&lig_glyphs[i])) { return OTS_FAILURE(); } if (lig_glyphs[i] >= length || lig_glyphs[i] < lig_glyphs_end) { return OTS_FAILURE(); } } // Parse coverage table if (!ots::ParseCoverageTable(data + offset_coverage, length - offset_coverage, num_glyphs)) { return OTS_FAILURE(); } // Parse ligature glyph table for (unsigned i = 0; i < lig_glyphs.size(); ++i) { subtable.set_offset(lig_glyphs[i]); uint16_t caret_count = 0; if (!subtable.ReadU16(&caret_count)) { return OTS_FAILURE(); } if (caret_count == 0) { OTS_WARNING("bad caret value count: %u", caret_count); return OTS_FAILURE(); } std::vector<uint16_t> caret_values; caret_values.resize(caret_count); uint16_t last_offset_caret = 0; unsigned caret_values_end = static_cast<unsigned>(2) * 2*caret_count; for (unsigned j = 0; j < caret_count; ++j) { if (!subtable.ReadU16(&caret_values[j])) { return OTS_FAILURE(); } if (caret_values[j] >= length || caret_values[j] < caret_values_end) { return OTS_FAILURE(); } // Caret offsets are in increasing coordinate order if (last_offset_caret != 0 && last_offset_caret >= caret_values[j]) { OTS_WARNING("offset isn't in increasing coordinate order: %u >= %u", last_offset_caret, caret_values[j]); return OTS_FAILURE(); } last_offset_caret = caret_values[j]; } // Parse caret values table for (unsigned j = 0; j < caret_count; ++j) { subtable.set_offset(lig_glyphs[i] + caret_values[j]); uint16_t caret_format = 0; if (!subtable.ReadU16(&caret_format)) { return OTS_FAILURE(); } // TODO(bashi): We only support caret value format 1 and 2 for now // because there are no fonts which contain caret value format 3 // as far as we investigated. if (caret_format == 0 || caret_format > kMaxCaretValueFormat) { OTS_WARNING("bad caret value format: %u", caret_format); return OTS_FAILURE(); } // CaretValueFormats contain a 2-byte field which could be // arbitrary value. if (!subtable.Skip(2)) { return OTS_FAILURE(); } } } return true; } bool ParseMarkAttachClassDefTable(ots::OpenTypeFile *file, const uint8_t *data, size_t length, const uint16_t num_glyphs) { return ots::ParseClassDefTable(data, length, num_glyphs, kMaxClassDefValue); } bool ParseMarkGlyphSetsDefTable(ots::OpenTypeFile *file, const uint8_t *data, size_t length, const uint16_t num_glyphs) { ots::Buffer subtable(data, length); uint16_t format = 0; uint16_t mark_set_count = 0; if (!subtable.ReadU16(&format) || !subtable.ReadU16(&mark_set_count)) { return OTS_FAILURE(); } if (format != 1) { OTS_WARNING("bad mark glyph set table format: %u", format); return OTS_FAILURE(); } const unsigned mark_sets_end = static_cast<unsigned>(4) + 2*mark_set_count; if (mark_sets_end > std::numeric_limits<uint16_t>::max()) { return OTS_FAILURE(); } for (unsigned i = 0; i < mark_set_count; ++i) { uint32_t offset_coverage = 0; if (!subtable.ReadU32(&offset_coverage)) { return OTS_FAILURE(); } if (offset_coverage >= length || offset_coverage < mark_sets_end) { return OTS_FAILURE(); } if (!ots::ParseCoverageTable(data + offset_coverage, length - offset_coverage, num_glyphs)) { return OTS_FAILURE(); } } file->gdef->num_mark_glyph_sets = mark_set_count; return true; } } // namespace #define DROP_THIS_TABLE \ do { file->gdef->data = 0; file->gdef->length = 0; } while (0) namespace ots { bool ots_gdef_parse(OpenTypeFile *file, const uint8_t *data, size_t length) { // Grab the number of glyphs in the file from the maxp table to check // GlyphIDs in GDEF table. if (!file->maxp) { return OTS_FAILURE(); } const uint16_t num_glyphs = file->maxp->num_glyphs; Buffer table(data, length); OpenTypeGDEF *gdef = new OpenTypeGDEF; file->gdef = gdef; uint32_t version = 0; if (!table.ReadU32(&version)) { return OTS_FAILURE(); } if (version < 0x00010000 || version == 0x00010001) { OTS_WARNING("bad GDEF version"); DROP_THIS_TABLE; return true; } if (version >= 0x00010002) { gdef->version_2 = true; } uint16_t offset_glyph_class_def = 0; uint16_t offset_attach_list = 0; uint16_t offset_lig_caret_list = 0; uint16_t offset_mark_attach_class_def = 0; if (!table.ReadU16(&offset_glyph_class_def) || !table.ReadU16(&offset_attach_list) || !table.ReadU16(&offset_lig_caret_list) || !table.ReadU16(&offset_mark_attach_class_def)) { return OTS_FAILURE(); } uint16_t offset_mark_glyph_sets_def = 0; if (gdef->version_2) { if (!table.ReadU16(&offset_mark_glyph_sets_def)) { return OTS_FAILURE(); } } const unsigned gdef_header_end = static_cast<unsigned>(8) + gdef->version_2 ? static_cast<unsigned>(2) : static_cast<unsigned>(0); if (gdef_header_end > std::numeric_limits<uint16_t>::max()) { return OTS_FAILURE(); } // Parse subtables if (offset_glyph_class_def) { if (offset_glyph_class_def >= length || offset_glyph_class_def < gdef_header_end) { return OTS_FAILURE(); } if (!ParseGlyphClassDefTable(file, data + offset_glyph_class_def, length - offset_glyph_class_def, num_glyphs)) { DROP_THIS_TABLE; return true; } gdef->has_glyph_class_def = true; } if (offset_attach_list) { if (offset_attach_list >= length || offset_attach_list < gdef_header_end) { return OTS_FAILURE(); } if (!ParseAttachListTable(file, data + offset_attach_list, length - offset_attach_list, num_glyphs)) { DROP_THIS_TABLE; return true; } } if (offset_lig_caret_list) { if (offset_lig_caret_list >= length || offset_lig_caret_list < gdef_header_end) { return OTS_FAILURE(); } if (!ParseLigCaretListTable(file, data + offset_lig_caret_list, length - offset_lig_caret_list, num_glyphs)) { DROP_THIS_TABLE; return true; } } if (offset_mark_attach_class_def) { if (offset_mark_attach_class_def >= length || offset_mark_attach_class_def < gdef_header_end) { return OTS_FAILURE(); } if (!ParseMarkAttachClassDefTable(file, data + offset_mark_attach_class_def, length - offset_mark_attach_class_def, num_glyphs)) { DROP_THIS_TABLE; return true; } gdef->has_mark_attachment_class_def = true; } if (offset_mark_glyph_sets_def) { if (offset_mark_glyph_sets_def >= length || offset_mark_glyph_sets_def < gdef_header_end) { return OTS_FAILURE(); } if (!ParseMarkGlyphSetsDefTable(file, data + offset_mark_glyph_sets_def, length - offset_mark_glyph_sets_def, num_glyphs)) { DROP_THIS_TABLE; return true; } gdef->has_mark_glyph_sets_def = true; } gdef->data = data; gdef->length = length; return true; } bool ots_gdef_should_serialise(OpenTypeFile *file) { const bool needed_tables_dropped = (file->gsub && file->gsub->data == NULL) || (file->gpos && file->gpos->data == NULL); return file->gdef != NULL && file->gdef->data != NULL && !needed_tables_dropped; } bool ots_gdef_serialise(OTSStream *out, OpenTypeFile *file) { if (!out->Write(file->gdef->data, file->gdef->length)) { return OTS_FAILURE(); } return true; } void ots_gdef_free(OpenTypeFile *file) { delete file->gdef; } } // namespace ots <commit_msg>Bug fix: + binds tighter than ?:<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gdef.h" #include <limits> #include <vector> #include "gpos.h" #include "gsub.h" #include "layout.h" #include "maxp.h" // GDEF - The Glyph Definition Table // http://www.microsoft.com/typography/otspec/gdef.htm namespace { // The maximum class value in class definition tables. const uint16_t kMaxClassDefValue = 0xFFFF; // The maximum class value in the glyph class definision table. const uint16_t kMaxGlyphClassDefValue = 4; // The maximum format number of caret value tables. // We don't support format 3 for now. See the comment in // ParseLigCaretListTable() for the reason. const uint16_t kMaxCaretValueFormat = 2; bool ParseGlyphClassDefTable(ots::OpenTypeFile *file, const uint8_t *data, size_t length, const uint16_t num_glyphs) { return ots::ParseClassDefTable(data, length, num_glyphs, kMaxGlyphClassDefValue); } bool ParseAttachListTable(ots::OpenTypeFile *file, const uint8_t *data, size_t length, const uint16_t num_glyphs) { ots::Buffer subtable(data, length); uint16_t offset_coverage = 0; uint16_t glyph_count = 0; if (!subtable.ReadU16(&offset_coverage) || !subtable.ReadU16(&glyph_count)) { return OTS_FAILURE(); } const unsigned attach_points_end = static_cast<unsigned>(4) + 2*glyph_count; if (attach_points_end > std::numeric_limits<uint16_t>::max()) { return OTS_FAILURE(); } if (offset_coverage == 0 || offset_coverage >= length || offset_coverage < attach_points_end) { return OTS_FAILURE(); } if (glyph_count > num_glyphs) { OTS_WARNING("bad glyph count: %u", glyph_count); return OTS_FAILURE(); } std::vector<uint16_t> attach_points; attach_points.resize(glyph_count); for (unsigned i = 0; i < glyph_count; ++i) { if (!subtable.ReadU16(&attach_points[i])) { return OTS_FAILURE(); } if (attach_points[i] >= length || attach_points[i] < attach_points_end) { return OTS_FAILURE(); } } // Parse coverage table if (!ots::ParseCoverageTable(data + offset_coverage, length - offset_coverage, num_glyphs)) { return OTS_FAILURE(); } // Parse attach point table for (unsigned i = 0; i < attach_points.size(); ++i) { subtable.set_offset(attach_points[i]); uint16_t point_count = 0; if (!subtable.ReadU16(&point_count)) { return OTS_FAILURE(); } if (point_count == 0) { return OTS_FAILURE(); } uint16_t last_point_index = 0; uint16_t point_index = 0; for (unsigned j = 0; j < point_count; ++j) { if (!subtable.ReadU16(&point_index)) { return OTS_FAILURE(); } // Contour point indeces are in increasing numerical order if (last_point_index != 0 && last_point_index >= point_index) { OTS_WARNING("bad contour indeces: %u >= %u", last_point_index, point_index); return OTS_FAILURE(); } last_point_index = point_index; } } return true; } bool ParseLigCaretListTable(ots::OpenTypeFile *file, const uint8_t *data, size_t length, const uint16_t num_glyphs) { ots::Buffer subtable(data, length); uint16_t offset_coverage = 0; uint16_t lig_glyph_count = 0; if (!subtable.ReadU16(&offset_coverage) || !subtable.ReadU16(&lig_glyph_count)) { return OTS_FAILURE(); } const unsigned lig_glyphs_end = static_cast<unsigned>(4) + 2*lig_glyph_count; if (lig_glyphs_end > std::numeric_limits<uint16_t>::max()) { return OTS_FAILURE(); } if (offset_coverage == 0 || offset_coverage >= length || offset_coverage < lig_glyphs_end) { return OTS_FAILURE(); } if (lig_glyph_count > num_glyphs) { OTS_WARNING("bad ligature glyph count: %u", lig_glyph_count); return OTS_FAILURE(); } std::vector<uint16_t> lig_glyphs; lig_glyphs.resize(lig_glyph_count); for (unsigned i = 0; i < lig_glyph_count; ++i) { if (!subtable.ReadU16(&lig_glyphs[i])) { return OTS_FAILURE(); } if (lig_glyphs[i] >= length || lig_glyphs[i] < lig_glyphs_end) { return OTS_FAILURE(); } } // Parse coverage table if (!ots::ParseCoverageTable(data + offset_coverage, length - offset_coverage, num_glyphs)) { return OTS_FAILURE(); } // Parse ligature glyph table for (unsigned i = 0; i < lig_glyphs.size(); ++i) { subtable.set_offset(lig_glyphs[i]); uint16_t caret_count = 0; if (!subtable.ReadU16(&caret_count)) { return OTS_FAILURE(); } if (caret_count == 0) { OTS_WARNING("bad caret value count: %u", caret_count); return OTS_FAILURE(); } std::vector<uint16_t> caret_values; caret_values.resize(caret_count); uint16_t last_offset_caret = 0; unsigned caret_values_end = static_cast<unsigned>(2) * 2*caret_count; for (unsigned j = 0; j < caret_count; ++j) { if (!subtable.ReadU16(&caret_values[j])) { return OTS_FAILURE(); } if (caret_values[j] >= length || caret_values[j] < caret_values_end) { return OTS_FAILURE(); } // Caret offsets are in increasing coordinate order if (last_offset_caret != 0 && last_offset_caret >= caret_values[j]) { OTS_WARNING("offset isn't in increasing coordinate order: %u >= %u", last_offset_caret, caret_values[j]); return OTS_FAILURE(); } last_offset_caret = caret_values[j]; } // Parse caret values table for (unsigned j = 0; j < caret_count; ++j) { subtable.set_offset(lig_glyphs[i] + caret_values[j]); uint16_t caret_format = 0; if (!subtable.ReadU16(&caret_format)) { return OTS_FAILURE(); } // TODO(bashi): We only support caret value format 1 and 2 for now // because there are no fonts which contain caret value format 3 // as far as we investigated. if (caret_format == 0 || caret_format > kMaxCaretValueFormat) { OTS_WARNING("bad caret value format: %u", caret_format); return OTS_FAILURE(); } // CaretValueFormats contain a 2-byte field which could be // arbitrary value. if (!subtable.Skip(2)) { return OTS_FAILURE(); } } } return true; } bool ParseMarkAttachClassDefTable(ots::OpenTypeFile *file, const uint8_t *data, size_t length, const uint16_t num_glyphs) { return ots::ParseClassDefTable(data, length, num_glyphs, kMaxClassDefValue); } bool ParseMarkGlyphSetsDefTable(ots::OpenTypeFile *file, const uint8_t *data, size_t length, const uint16_t num_glyphs) { ots::Buffer subtable(data, length); uint16_t format = 0; uint16_t mark_set_count = 0; if (!subtable.ReadU16(&format) || !subtable.ReadU16(&mark_set_count)) { return OTS_FAILURE(); } if (format != 1) { OTS_WARNING("bad mark glyph set table format: %u", format); return OTS_FAILURE(); } const unsigned mark_sets_end = static_cast<unsigned>(4) + 2*mark_set_count; if (mark_sets_end > std::numeric_limits<uint16_t>::max()) { return OTS_FAILURE(); } for (unsigned i = 0; i < mark_set_count; ++i) { uint32_t offset_coverage = 0; if (!subtable.ReadU32(&offset_coverage)) { return OTS_FAILURE(); } if (offset_coverage >= length || offset_coverage < mark_sets_end) { return OTS_FAILURE(); } if (!ots::ParseCoverageTable(data + offset_coverage, length - offset_coverage, num_glyphs)) { return OTS_FAILURE(); } } file->gdef->num_mark_glyph_sets = mark_set_count; return true; } } // namespace #define DROP_THIS_TABLE \ do { file->gdef->data = 0; file->gdef->length = 0; } while (0) namespace ots { bool ots_gdef_parse(OpenTypeFile *file, const uint8_t *data, size_t length) { // Grab the number of glyphs in the file from the maxp table to check // GlyphIDs in GDEF table. if (!file->maxp) { return OTS_FAILURE(); } const uint16_t num_glyphs = file->maxp->num_glyphs; Buffer table(data, length); OpenTypeGDEF *gdef = new OpenTypeGDEF; file->gdef = gdef; uint32_t version = 0; if (!table.ReadU32(&version)) { return OTS_FAILURE(); } if (version < 0x00010000 || version == 0x00010001) { OTS_WARNING("bad GDEF version"); DROP_THIS_TABLE; return true; } if (version >= 0x00010002) { gdef->version_2 = true; } uint16_t offset_glyph_class_def = 0; uint16_t offset_attach_list = 0; uint16_t offset_lig_caret_list = 0; uint16_t offset_mark_attach_class_def = 0; if (!table.ReadU16(&offset_glyph_class_def) || !table.ReadU16(&offset_attach_list) || !table.ReadU16(&offset_lig_caret_list) || !table.ReadU16(&offset_mark_attach_class_def)) { return OTS_FAILURE(); } uint16_t offset_mark_glyph_sets_def = 0; if (gdef->version_2) { if (!table.ReadU16(&offset_mark_glyph_sets_def)) { return OTS_FAILURE(); } } unsigned gdef_header_end = 8; if (gdef->version_2) gdef_header_end += 2; // Parse subtables if (offset_glyph_class_def) { if (offset_glyph_class_def >= length || offset_glyph_class_def < gdef_header_end) { return OTS_FAILURE(); } if (!ParseGlyphClassDefTable(file, data + offset_glyph_class_def, length - offset_glyph_class_def, num_glyphs)) { DROP_THIS_TABLE; return true; } gdef->has_glyph_class_def = true; } if (offset_attach_list) { if (offset_attach_list >= length || offset_attach_list < gdef_header_end) { return OTS_FAILURE(); } if (!ParseAttachListTable(file, data + offset_attach_list, length - offset_attach_list, num_glyphs)) { DROP_THIS_TABLE; return true; } } if (offset_lig_caret_list) { if (offset_lig_caret_list >= length || offset_lig_caret_list < gdef_header_end) { return OTS_FAILURE(); } if (!ParseLigCaretListTable(file, data + offset_lig_caret_list, length - offset_lig_caret_list, num_glyphs)) { DROP_THIS_TABLE; return true; } } if (offset_mark_attach_class_def) { if (offset_mark_attach_class_def >= length || offset_mark_attach_class_def < gdef_header_end) { return OTS_FAILURE(); } if (!ParseMarkAttachClassDefTable(file, data + offset_mark_attach_class_def, length - offset_mark_attach_class_def, num_glyphs)) { DROP_THIS_TABLE; return true; } gdef->has_mark_attachment_class_def = true; } if (offset_mark_glyph_sets_def) { if (offset_mark_glyph_sets_def >= length || offset_mark_glyph_sets_def < gdef_header_end) { return OTS_FAILURE(); } if (!ParseMarkGlyphSetsDefTable(file, data + offset_mark_glyph_sets_def, length - offset_mark_glyph_sets_def, num_glyphs)) { DROP_THIS_TABLE; return true; } gdef->has_mark_glyph_sets_def = true; } gdef->data = data; gdef->length = length; return true; } bool ots_gdef_should_serialise(OpenTypeFile *file) { const bool needed_tables_dropped = (file->gsub && file->gsub->data == NULL) || (file->gpos && file->gpos->data == NULL); return file->gdef != NULL && file->gdef->data != NULL && !needed_tables_dropped; } bool ots_gdef_serialise(OTSStream *out, OpenTypeFile *file) { if (!out->Write(file->gdef->data, file->gdef->length)) { return OTS_FAILURE(); } return true; } void ots_gdef_free(OpenTypeFile *file) { delete file->gdef; } } // namespace ots <|endoftext|>
<commit_before>#include "grid.h" #include <stdlib.h> #include <chrono> #include <iostream> #include <thread> #include "cell.h" Grid::Grid(int width, int height, int renderDelay) { this->width = width; this->height = height; this->renderDelay = renderDelay; window = newwin(width * 2 + 10, height * 2 + 10, 0, 0); createCells(); current = &cells[0]; } void Grid::createCells() { for (int row = 0; row < height; row++) { for (int column = 0; column < width; column++) { cells.push_back(Cell(row, column)); } } } void Grid::generateMaze() { while (true) { current->setVisited(true); Cell *next = findNextCell(); if (next != NULL) { next->setVisited(true); backtrace.push(current); current->removeWalls(*next); current = next; } else if (backtrace.size() > 0) { current = backtrace.top(); backtrace.pop(); } else if (backtrace.size() == 0) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(renderDelay)); werase(window); render(); } } void Grid::render() { for (Cell c : cells) { c.show(window); wmove(window, (current->getRow()) + 1, ((current->getColumn()) + 2) + (current->getColumn())); } refresh(); wrefresh(window); } Cell *Grid::findNextCell() { std::vector<Cell *> availableNeighbors = getAvailableNeighbors(); if (availableNeighbors.size() > 0) { return availableNeighbors.at(rand() % availableNeighbors.size()); } return NULL; } std::vector<Cell *> Grid::getAvailableNeighbors() { std::vector<Cell *> neighbors; int currentRow = current->getRow(); int currentColumn = current->getColumn(); int neighborIndexes[4] = { calculateIndex(currentRow - 1, currentColumn), calculateIndex(currentRow, currentColumn + 1), calculateIndex(currentRow + 1, currentColumn), calculateIndex(currentRow, currentColumn - 1), }; for (int i : neighborIndexes) { if (i != -1 && !cells[i].isVisited()) { neighbors.push_back(&cells[i]); } } return neighbors; } int Grid::calculateIndex(int row, int column) { if (row < 0 || column < 0 || column > width - 1 || row > height - 1) return -1; else return column + row * width; } <commit_msg>Correcting the size of the window.<commit_after>#include "grid.h" #include <stdlib.h> #include <chrono> #include <iostream> #include <thread> #include "cell.h" Grid::Grid(int width, int height, int renderDelay) { this->width = width; this->height = height; this->renderDelay = renderDelay; window = newwin(height * 2 + 10, width * 2 + 10, 0, 0); createCells(); current = &cells[0]; } void Grid::createCells() { for (int row = 0; row < height; row++) { for (int column = 0; column < width; column++) { cells.push_back(Cell(row, column)); } } } void Grid::generateMaze() { while (true) { current->setVisited(true); Cell *next = findNextCell(); if (next != NULL) { next->setVisited(true); backtrace.push(current); current->removeWalls(*next); current = next; } else if (backtrace.size() > 0) { current = backtrace.top(); backtrace.pop(); } else if (backtrace.size() == 0) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(renderDelay)); werase(window); render(); } } void Grid::render() { for (Cell c : cells) { c.show(window); wmove(window, (current->getRow()) + 1, ((current->getColumn()) + 2) + (current->getColumn())); } refresh(); wrefresh(window); } Cell *Grid::findNextCell() { std::vector<Cell *> availableNeighbors = getAvailableNeighbors(); if (availableNeighbors.size() > 0) { return availableNeighbors.at(rand() % availableNeighbors.size()); } return NULL; } std::vector<Cell *> Grid::getAvailableNeighbors() { std::vector<Cell *> neighbors; int currentRow = current->getRow(); int currentColumn = current->getColumn(); int neighborIndexes[4] = { calculateIndex(currentRow - 1, currentColumn), calculateIndex(currentRow, currentColumn + 1), calculateIndex(currentRow + 1, currentColumn), calculateIndex(currentRow, currentColumn - 1), }; for (int i : neighborIndexes) { if (i != -1 && !cells[i].isVisited()) { neighbors.push_back(&cells[i]); } } return neighbors; } int Grid::calculateIndex(int row, int column) { if (row < 0 || column < 0 || column > width - 1 || row > height - 1) return -1; else return column + row * width; } <|endoftext|>
<commit_before> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <unistd.h> #include <fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/types.h> #include <signal.h> #include <errno.h> #include "utils.hpp" #include "worker_pool.hpp" #include "async_io.hpp" #include "alloc_blackhole.hpp" void event_handler(event_queue_t *event_queue, event_t *event) { int res; size_t sz; char buf[256]; if(event->event_type == et_sock_event) { bzero(buf, sizeof(buf)); // TODO: make sure we don't leave any data in the socket sz = read(event->source, buf, sizeof(buf)); check("Could not read from socket", sz == -1); if(sz > 0) { printf("(worker: %d, size: %d) Msg: %s", event_queue->queue_id, (int)sz, buf); // See if we have a quit message if(strncmp(buf, "quit", 4) == 0) { printf("Quitting server...\n"); res = pthread_kill(event_queue->parent_pool->main_thread, SIGTERM); check("Could not send kill signal to main thread", res != 0); return; } // Allocate a buffer to read file into size_t old_alignment = get_alignment(&event_queue->allocator); set_alignment(&event_queue->allocator, 512); void *gbuf = malloc(&event_queue->allocator, 512); set_alignment(&event_queue->allocator, old_alignment); // Fire off an async IO event bzero(gbuf, 512); int offset = atoi(buf); schedule_aio_read((int)(long)event_queue->parent_pool->data, offset, 512, gbuf, event_queue, (void*)event->source, &event_queue->allocator); } else { // No data left, close the socket printf("Closing socket %d\n", event->source); queue_forget_resource(event_queue, event->source); close(event->source); } } else { // We got async IO event back if(event->result < 0) { printf("File notify (fd %d, res: %d) %s\n", event->source, event->result, strerror(-event->result)); } else { ((char*)event->buf)[11] = 0; printf("File notify (fd %d, res: %d) %s\n", event->source, event->result, (char*)event->buf); res = write((int)(long)event->state, event->buf, 10); check("Could not write to socket", res == -1); } } } void term_handler(int signum) { // Do nothing, we'll naturally break out of the main loop because // the accept syscall will get interrupted. } /****** * Socket handling **/ void process_socket(int sockfd, worker_pool_t *worker_pool) { event_queue_t *event_queue = next_active_worker(worker_pool); queue_watch_resource(event_queue, sockfd, NULL); printf("Connected to socket %d\n", sockfd); } int main(int argc, char *argv[]) { int res; // Setup termination handlers struct sigaction action; bzero((char*)&action, sizeof(action)); action.sa_handler = term_handler; res = sigaction(SIGTERM, &action, NULL); check("Could not install TERM handler", res < 0); bzero((char*)&action, sizeof(action)); action.sa_handler = term_handler; res = sigaction(SIGINT, &action, NULL); check("Could not install INT handler", res < 0); // Create a pool of workers worker_pool_t worker_pool; worker_pool.data = (void*)open("leo.txt", O_DIRECT | O_NOATIME | O_RDONLY); create_worker_pool(&worker_pool, event_handler, pthread_self()); // Create the socket int sockfd; sockfd = socket(AF_INET, SOCK_STREAM, 0); check("Couldn't create socket", sockfd == -1); int sockoptval = 1; res = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &sockoptval, sizeof(sockoptval)); check("Could not set REUSEADDR option", res == -1); // Bind the socket sockaddr_in serv_addr; bzero((char*)&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(8080); serv_addr.sin_addr.s_addr = INADDR_ANY; res = bind(sockfd, (sockaddr*)&serv_addr, sizeof(serv_addr)); check("Couldn't bind socket", res != 0); // Start listening to connections res = listen(sockfd, 5); check("Couldn't listen to the socket", res != 0); // Accept incoming connections while(1) { // TODO: add a sound way to get out of this loop int newsockfd; sockaddr_in client_addr; socklen_t client_addr_len = sizeof(client_addr); newsockfd = accept(sockfd, (sockaddr*)&client_addr, &client_addr_len); // Break out of the loop on sigterm if(newsockfd == -1 && errno == EINTR) break; check("Could not accept connection", newsockfd == -1); // Process the socket res = fcntl(newsockfd, F_SETFL, O_NONBLOCK); check("Could not make socket non-blocking", res != 0); process_socket(newsockfd, &worker_pool); } // Cleanup the resources destroy_worker_pool(&worker_pool); res = shutdown(sockfd, SHUT_RDWR); check("Could not shutdown main socket", res == -1); res = close(sockfd); check("Could not close main socket", res != 0); res = close((int)(long)worker_pool.data); check("Could not close served file", res != 0); printf("Server offline\n"); } <commit_msg>Removing unnecessary printf's<commit_after> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <unistd.h> #include <fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/types.h> #include <signal.h> #include <errno.h> #include "utils.hpp" #include "worker_pool.hpp" #include "async_io.hpp" #include "alloc_blackhole.hpp" void event_handler(event_queue_t *event_queue, event_t *event) { int res; size_t sz; char buf[256]; if(event->event_type == et_sock_event) { bzero(buf, sizeof(buf)); // TODO: make sure we don't leave any data in the socket sz = read(event->source, buf, sizeof(buf)); check("Could not read from socket", sz == -1); if(sz > 0) { // See if we have a quit message if(strncmp(buf, "quit", 4) == 0) { printf("Quitting server...\n"); res = pthread_kill(event_queue->parent_pool->main_thread, SIGTERM); check("Could not send kill signal to main thread", res != 0); return; } // Allocate a buffer to read file into size_t old_alignment = get_alignment(&event_queue->allocator); set_alignment(&event_queue->allocator, 512); void *gbuf = malloc(&event_queue->allocator, 512); set_alignment(&event_queue->allocator, old_alignment); // Fire off an async IO event bzero(gbuf, 512); int offset = atoi(buf); schedule_aio_read((int)(long)event_queue->parent_pool->data, offset, 512, gbuf, event_queue, (void*)event->source, &event_queue->allocator); } else { // No data left, close the socket printf("Closing socket %d\n", event->source); queue_forget_resource(event_queue, event->source); close(event->source); } } else { // We got async IO event back if(event->result < 0) { printf("File notify error (fd %d, res: %d) %s\n", event->source, event->result, strerror(-event->result)); } else { ((char*)event->buf)[11] = 0; res = write((int)(long)event->state, event->buf, 10); check("Could not write to socket", res == -1); } } } void term_handler(int signum) { // Do nothing, we'll naturally break out of the main loop because // the accept syscall will get interrupted. } /****** * Socket handling **/ void process_socket(int sockfd, worker_pool_t *worker_pool) { event_queue_t *event_queue = next_active_worker(worker_pool); queue_watch_resource(event_queue, sockfd, NULL); } int main(int argc, char *argv[]) { int res; // Setup termination handlers struct sigaction action; bzero((char*)&action, sizeof(action)); action.sa_handler = term_handler; res = sigaction(SIGTERM, &action, NULL); check("Could not install TERM handler", res < 0); bzero((char*)&action, sizeof(action)); action.sa_handler = term_handler; res = sigaction(SIGINT, &action, NULL); check("Could not install INT handler", res < 0); // Create a pool of workers worker_pool_t worker_pool; worker_pool.data = (void*)open("leo.txt", O_DIRECT | O_NOATIME | O_RDONLY); create_worker_pool(&worker_pool, event_handler, pthread_self()); // Create the socket int sockfd; sockfd = socket(AF_INET, SOCK_STREAM, 0); check("Couldn't create socket", sockfd == -1); int sockoptval = 1; res = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &sockoptval, sizeof(sockoptval)); check("Could not set REUSEADDR option", res == -1); // Bind the socket sockaddr_in serv_addr; bzero((char*)&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(8080); serv_addr.sin_addr.s_addr = INADDR_ANY; res = bind(sockfd, (sockaddr*)&serv_addr, sizeof(serv_addr)); check("Couldn't bind socket", res != 0); // Start listening to connections res = listen(sockfd, 5); check("Couldn't listen to the socket", res != 0); // Accept incoming connections while(1) { // TODO: add a sound way to get out of this loop int newsockfd; sockaddr_in client_addr; socklen_t client_addr_len = sizeof(client_addr); newsockfd = accept(sockfd, (sockaddr*)&client_addr, &client_addr_len); // Break out of the loop on sigterm if(newsockfd == -1 && errno == EINTR) break; check("Could not accept connection", newsockfd == -1); // Process the socket res = fcntl(newsockfd, F_SETFL, O_NONBLOCK); check("Could not make socket non-blocking", res != 0); process_socket(newsockfd, &worker_pool); } // Cleanup the resources destroy_worker_pool(&worker_pool); res = shutdown(sockfd, SHUT_RDWR); check("Could not shutdown main socket", res == -1); res = close(sockfd); check("Could not close main socket", res != 0); res = close((int)(long)worker_pool.data); check("Could not close served file", res != 0); printf("Server offline\n"); } <|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. All rights reserved. // Use of this source code is governed by MIT license that can be found in the // LICENSE file. #include <string.h> #include "rescle.h" #include "version.h" namespace { void print_help() { fprintf(stdout, "Rcedit " RCEDIT_VERSION ":\n"); } bool print_error(const char* message) { fprintf(stderr, "Fatal error: %s\n", message); return 1; } bool print_warning(const char* message) { fprintf(stderr, "Warning: %s\n", message); return 1; } bool parse_version_string(const wchar_t* str, unsigned short *v1, unsigned short *v2, unsigned short *v3, unsigned short *v4) { *v1 = *v2 = *v3 = *v4 = 0; return (swscanf_s(str, L"%hu.%hu.%hu.%hu", v1, v2, v3, v4) == 4) || (swscanf_s(str, L"%hu.%hu.%hu", v1, v2, v3) == 3) || (swscanf_s(str, L"%hu.%hu", v1, v2) == 2) || (swscanf_s(str, L"%hu", v1) == 1); } } // namespace int wmain(int argc, const wchar_t* argv[]) { bool loaded = false; rescle::ResourceUpdater updater; if (argc == 1 || (argc == 2 && wcscmp(argv[1], L"-h") == 0) || (argc == 2 && wcscmp(argv[1], L"--help") == 0)) { print_help(); return 0; } for (int i = 1; i < argc; ++i) { if (wcscmp(argv[i], L"--set-version-string") == 0 || wcscmp(argv[i], L"-svs") == 0) { if (argc - i < 3) return print_error("--set-version-string requires 'Key' and 'Value'"); const wchar_t* key = argv[++i]; const wchar_t* value = argv[++i]; if (!updater.SetVersionString(key, value)) return print_error("Unable to change version string"); } else if (wcscmp(argv[i], L"--get-version-string") == 0 || wcscmp(argv[i], L"-gvs") == 0) { if (argc - i < 2) return print_error("--get-version-string requires 'Key'"); const wchar_t* key = argv[++i]; const wchar_t* result = updater.GetVersionString(key); if (!result) return print_error("Unable to get version string"); fwprintf(stdout, L"%s", result); return 0; // no changes made } else if (wcscmp(argv[i], L"--set-file-version") == 0 || wcscmp(argv[i], L"-sfv") == 0) { if (argc - i < 2) return print_error("--set-file-version requires a version string"); unsigned short v1, v2, v3, v4; if (!parse_version_string(argv[++i], &v1, &v2, &v3, &v4)) return print_error("Unable to parse version string for FileVersion"); if (!updater.SetFileVersion(v1, v2, v3, v4)) return print_error("Unable to change file version"); if (!updater.SetVersionString(L"FileVersion", argv[i])) return print_error("Unable to change FileVersion string"); } else if (wcscmp(argv[i], L"--set-product-version") == 0 || wcscmp(argv[i], L"-spv") == 0) { if (argc - i < 2) return print_error("--set-product-version requires a version string"); unsigned short v1, v2, v3, v4; if (!parse_version_string(argv[++i], &v1, &v2, &v3, &v4)) return print_error("Unable to parse version string for ProductVersion"); if (!updater.SetProductVersion(v1, v2, v3, v4)) return print_error("Unable to change product version"); if (!updater.SetVersionString(L"ProductVersion", argv[i])) return print_error("Unable to change ProductVersion string"); } else if (wcscmp(argv[i], L"--set-icon") == 0 || wcscmp(argv[i], L"-si") == 0) { if (argc - i < 2) return print_error("--set-icon requires path to the icon"); if (!updater.SetIcon(argv[++i])) return print_error("Unable to set icon"); } else if (wcscmp(argv[i], L"--set-requested-execution-level") == 0 || wcscmp(argv[i], L"-srel") == 0) { if (argc - i < 2) return print_error("--set-requested-execution-level requires asInvoker, highestAvailable or requireAdministrator"); if (updater.IsApplicationManifestSet()) print_warning("--set-requested-execution-level is ignored if --application-manifest is set"); if (!updater.SetExecutionLevel(argv[++i])) return print_error("Unable to set execution level"); } else if (wcscmp(argv[i], L"--application-manifest") == 0 || wcscmp(argv[i], L"-am") == 0) { if (argc - i < 2) return print_error("--application-manifest requires local path"); if (updater.IsExecutionLevelSet()) print_warning("--set-requested-execution-level is ignored if --application-manifest is set"); if (!updater.SetApplicationManifest(argv[++i])) return print_error("Unable to set application manifest"); } else if (wcscmp(argv[i], L"--set-resource-string") == 0 || wcscmp(argv[i], L"--srs") == 0) { if (argc - i < 3) return print_error("--set-resource-string requires int 'Key' and string 'Value'"); const wchar_t* key = argv[++i]; unsigned int key_id = 0; if (swscanf_s(key, L"%d", &key_id) != 1) return print_error("Unable to parse id"); const wchar_t* value = argv[++i]; if (!updater.ChangeString(key_id, value)) return print_error("Unable to change string"); } else { if (loaded) return print_error("Unexpected trailing arguments"); loaded = true; if (!updater.Load(argv[i])) return print_error("Unable to load file"); } } if (!loaded) return print_error("You should specify a exe/dll file"); if (!updater.Commit()) return print_error("Unable to commit changes"); return 0; } <commit_msg>Better message for unhandled argument<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved. // Use of this source code is governed by MIT license that can be found in the // LICENSE file. #include <string.h> #include "rescle.h" #include "version.h" namespace { void print_help() { fprintf(stdout, "Rcedit " RCEDIT_VERSION ":\n"); } bool print_error(const char* message) { fprintf(stderr, "Fatal error: %s\n", message); return 1; } bool print_warning(const char* message) { fprintf(stderr, "Warning: %s\n", message); return 1; } bool parse_version_string(const wchar_t* str, unsigned short *v1, unsigned short *v2, unsigned short *v3, unsigned short *v4) { *v1 = *v2 = *v3 = *v4 = 0; return (swscanf_s(str, L"%hu.%hu.%hu.%hu", v1, v2, v3, v4) == 4) || (swscanf_s(str, L"%hu.%hu.%hu", v1, v2, v3) == 3) || (swscanf_s(str, L"%hu.%hu", v1, v2) == 2) || (swscanf_s(str, L"%hu", v1) == 1); } } // namespace int wmain(int argc, const wchar_t* argv[]) { bool loaded = false; rescle::ResourceUpdater updater; if (argc == 1 || (argc == 2 && wcscmp(argv[1], L"-h") == 0) || (argc == 2 && wcscmp(argv[1], L"--help") == 0)) { print_help(); return 0; } for (int i = 1; i < argc; ++i) { if (wcscmp(argv[i], L"--set-version-string") == 0 || wcscmp(argv[i], L"-svs") == 0) { if (argc - i < 3) return print_error("--set-version-string requires 'Key' and 'Value'"); const wchar_t* key = argv[++i]; const wchar_t* value = argv[++i]; if (!updater.SetVersionString(key, value)) return print_error("Unable to change version string"); } else if (wcscmp(argv[i], L"--get-version-string") == 0 || wcscmp(argv[i], L"-gvs") == 0) { if (argc - i < 2) return print_error("--get-version-string requires 'Key'"); const wchar_t* key = argv[++i]; const wchar_t* result = updater.GetVersionString(key); if (!result) return print_error("Unable to get version string"); fwprintf(stdout, L"%s", result); return 0; // no changes made } else if (wcscmp(argv[i], L"--set-file-version") == 0 || wcscmp(argv[i], L"-sfv") == 0) { if (argc - i < 2) return print_error("--set-file-version requires a version string"); unsigned short v1, v2, v3, v4; if (!parse_version_string(argv[++i], &v1, &v2, &v3, &v4)) return print_error("Unable to parse version string for FileVersion"); if (!updater.SetFileVersion(v1, v2, v3, v4)) return print_error("Unable to change file version"); if (!updater.SetVersionString(L"FileVersion", argv[i])) return print_error("Unable to change FileVersion string"); } else if (wcscmp(argv[i], L"--set-product-version") == 0 || wcscmp(argv[i], L"-spv") == 0) { if (argc - i < 2) return print_error("--set-product-version requires a version string"); unsigned short v1, v2, v3, v4; if (!parse_version_string(argv[++i], &v1, &v2, &v3, &v4)) return print_error("Unable to parse version string for ProductVersion"); if (!updater.SetProductVersion(v1, v2, v3, v4)) return print_error("Unable to change product version"); if (!updater.SetVersionString(L"ProductVersion", argv[i])) return print_error("Unable to change ProductVersion string"); } else if (wcscmp(argv[i], L"--set-icon") == 0 || wcscmp(argv[i], L"-si") == 0) { if (argc - i < 2) return print_error("--set-icon requires path to the icon"); if (!updater.SetIcon(argv[++i])) return print_error("Unable to set icon"); } else if (wcscmp(argv[i], L"--set-requested-execution-level") == 0 || wcscmp(argv[i], L"-srel") == 0) { if (argc - i < 2) return print_error("--set-requested-execution-level requires asInvoker, highestAvailable or requireAdministrator"); if (updater.IsApplicationManifestSet()) print_warning("--set-requested-execution-level is ignored if --application-manifest is set"); if (!updater.SetExecutionLevel(argv[++i])) return print_error("Unable to set execution level"); } else if (wcscmp(argv[i], L"--application-manifest") == 0 || wcscmp(argv[i], L"-am") == 0) { if (argc - i < 2) return print_error("--application-manifest requires local path"); if (updater.IsExecutionLevelSet()) print_warning("--set-requested-execution-level is ignored if --application-manifest is set"); if (!updater.SetApplicationManifest(argv[++i])) return print_error("Unable to set application manifest"); } else if (wcscmp(argv[i], L"--set-resource-string") == 0 || wcscmp(argv[i], L"--srs") == 0) { if (argc - i < 3) return print_error("--set-resource-string requires int 'Key' and string 'Value'"); const wchar_t* key = argv[++i]; unsigned int key_id = 0; if (swscanf_s(key, L"%d", &key_id) != 1) return print_error("Unable to parse id"); const wchar_t* value = argv[++i]; if (!updater.ChangeString(key_id, value)) return print_error("Unable to change string"); } else { if (loaded) return print_error("Unexpected trailing arguments"); loaded = true; if (!updater.Load(argv[i])) { fprintf(stderr, "Unable to load file: \"%ls\"\n", argv[i]); return 1; } } } if (!loaded) return print_error("You should specify a exe/dll file"); if (!updater.Commit()) return print_error("Unable to commit changes"); return 0; } <|endoftext|>
<commit_before><commit_msg>‘AddTask_for_root6’<commit_after><|endoftext|>
<commit_before><commit_msg>Added MC settings for HSE<commit_after><|endoftext|>
<commit_before>/* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng ([email protected]) * * This file is part of FlashMatrix. * * 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 <stdio.h> #include "data_frame.h" #include "mem_matrix_store.h" #include "sparse_matrix.h" #include "factor.h" #include "fmr_utils.h" #include "rutils.h" using namespace fm; /* * Clean up a sparse matrix. */ static void fm_clean_SpM(SEXP p) { object_ref<sparse_matrix> *ref = (object_ref<sparse_matrix> *) R_ExternalPtrAddr(p); delete ref; } /* * Clean up a dense matrix */ static void fm_clean_DM(SEXP p) { object_ref<dense_matrix> *ref = (object_ref<dense_matrix> *) R_ExternalPtrAddr(p); delete ref; } SEXP create_FMR_matrix(sparse_matrix::ptr m, const std::string &name) { Rcpp::List ret; ret["name"] = Rcpp::String(name); ret["type"] = Rcpp::String("sparse"); if (m->is_type<int>()) ret["ele_type"] = Rcpp::String("integer"); else if (m->is_type<double>()) ret["ele_type"] = Rcpp::String("double"); else if (m->is_type<bool>()) ret["ele_type"] = Rcpp::String("logical"); else ret["ele_type"] = Rcpp::String("unknown"); object_ref<sparse_matrix> *ref = new object_ref<sparse_matrix>(m); SEXP pointer = R_MakeExternalPtr(ref, R_NilValue, R_NilValue); R_RegisterCFinalizerEx(pointer, fm_clean_SpM, TRUE); ret["pointer"] = pointer; Rcpp::LogicalVector sym(1); sym[0] = m->is_symmetric(); ret["sym"] = sym; Rcpp::NumericVector nrow(1); nrow[0] = m->get_num_rows(); ret["nrow"] = nrow; Rcpp::NumericVector ncol(1); ncol[0] = m->get_num_cols(); ret["ncol"] = ncol; return ret; } SEXP create_FMR_matrix(dense_matrix::ptr m, const std::string &name) { Rcpp::List ret; ret["name"] = Rcpp::String(name); ret["type"] = Rcpp::String("dense"); if (m->is_type<int>()) ret["ele_type"] = Rcpp::String("integer"); else if (m->is_type<double>()) ret["ele_type"] = Rcpp::String("double"); else if (m->is_type<bool>()) { m = m->cast_ele_type(get_scalar_type<int>()); ret["ele_type"] = Rcpp::String("logical"); } else ret["ele_type"] = Rcpp::String("unknown"); object_ref<dense_matrix> *ref = new object_ref<dense_matrix>(m); SEXP pointer = R_MakeExternalPtr(ref, R_NilValue, R_NilValue); R_RegisterCFinalizerEx(pointer, fm_clean_DM, TRUE); ret["pointer"] = pointer; Rcpp::NumericVector nrow(1); nrow[0] = m->get_num_rows(); ret["nrow"] = nrow; Rcpp::NumericVector ncol(1); ncol[0] = m->get_num_cols(); ret["ncol"] = ncol; return ret; } SEXP create_FMR_vector(detail::vec_store::const_ptr vec, const std::string &name) { detail::matrix_store::const_ptr mat = vec->conv2mat(vec->get_length(), 1, false); return create_FMR_vector(dense_matrix::create( detail::mem_matrix_store::cast(mat)), name); } SEXP create_FMR_vector(dense_matrix::ptr m, const std::string &name) { Rcpp::List ret; ret["name"] = Rcpp::String(name); ret["type"] = Rcpp::String("vector"); if (m->is_type<int>()) ret["ele_type"] = Rcpp::String("integer"); else if (m->is_type<double>()) ret["ele_type"] = Rcpp::String("double"); else if (m->is_type<bool>()) { m = m->cast_ele_type(get_scalar_type<int>()); ret["ele_type"] = Rcpp::String("logical"); } else ret["ele_type"] = Rcpp::String("unknown"); object_ref<dense_matrix> *ref = new object_ref<dense_matrix>(m); SEXP pointer = R_MakeExternalPtr(ref, R_NilValue, R_NilValue); R_RegisterCFinalizerEx(pointer, fm_clean_DM, TRUE); ret["pointer"] = pointer; Rcpp::NumericVector len(1); if (m->get_num_cols() == 1) len[0] = m->get_num_rows(); else len[0] = m->get_num_cols(); ret["len"] = len; return ret; } factor_col_vector::ptr get_factor_vector(const Rcpp::S4 &vec) { if (!is_factor_vector(vec)) { fprintf(stderr, "The S4 object isn't a factor vector\n"); return factor_col_vector::ptr(); } object_ref<dense_matrix> *ref = (object_ref<dense_matrix> *) R_ExternalPtrAddr(vec.slot("pointer")); dense_matrix::ptr mat = ref->get_object(); // This should be a column matrix. assert(mat->get_num_cols() == 1); size_t num_levels = vec.slot("num.levels"); return factor_col_vector::create(factor(num_levels), mat); } col_vec::ptr get_vector(const Rcpp::S4 &vec) { dense_matrix::ptr mat = get_matrix<dense_matrix>(vec); if (mat->get_num_rows() > 1 && mat->get_num_cols() > 1) { fprintf(stderr, "The input object is a matrix"); return col_vec::ptr(); } return col_vec::create(mat); } SEXP create_FMR_data_frame(data_frame::ptr df, const std::string &name) { Rcpp::List ret; for (size_t i = 0; i < df->get_num_vecs(); i++) { std::string vec_name = df->get_vec_name(i); ret[vec_name] = create_FMR_vector(df->get_vec(i), vec_name); } return ret; } <commit_msg>[R]: FlashR vector is always a one-col matrix.<commit_after>/* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng ([email protected]) * * This file is part of FlashMatrix. * * 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 <stdio.h> #include "data_frame.h" #include "mem_matrix_store.h" #include "sparse_matrix.h" #include "factor.h" #include "fmr_utils.h" #include "rutils.h" using namespace fm; /* * Clean up a sparse matrix. */ static void fm_clean_SpM(SEXP p) { object_ref<sparse_matrix> *ref = (object_ref<sparse_matrix> *) R_ExternalPtrAddr(p); delete ref; } /* * Clean up a dense matrix */ static void fm_clean_DM(SEXP p) { object_ref<dense_matrix> *ref = (object_ref<dense_matrix> *) R_ExternalPtrAddr(p); delete ref; } SEXP create_FMR_matrix(sparse_matrix::ptr m, const std::string &name) { Rcpp::List ret; ret["name"] = Rcpp::String(name); ret["type"] = Rcpp::String("sparse"); if (m->is_type<int>()) ret["ele_type"] = Rcpp::String("integer"); else if (m->is_type<double>()) ret["ele_type"] = Rcpp::String("double"); else if (m->is_type<bool>()) ret["ele_type"] = Rcpp::String("logical"); else ret["ele_type"] = Rcpp::String("unknown"); object_ref<sparse_matrix> *ref = new object_ref<sparse_matrix>(m); SEXP pointer = R_MakeExternalPtr(ref, R_NilValue, R_NilValue); R_RegisterCFinalizerEx(pointer, fm_clean_SpM, TRUE); ret["pointer"] = pointer; Rcpp::LogicalVector sym(1); sym[0] = m->is_symmetric(); ret["sym"] = sym; Rcpp::NumericVector nrow(1); nrow[0] = m->get_num_rows(); ret["nrow"] = nrow; Rcpp::NumericVector ncol(1); ncol[0] = m->get_num_cols(); ret["ncol"] = ncol; return ret; } SEXP create_FMR_matrix(dense_matrix::ptr m, const std::string &name) { Rcpp::List ret; ret["name"] = Rcpp::String(name); ret["type"] = Rcpp::String("dense"); if (m->is_type<int>()) ret["ele_type"] = Rcpp::String("integer"); else if (m->is_type<double>()) ret["ele_type"] = Rcpp::String("double"); else if (m->is_type<bool>()) { m = m->cast_ele_type(get_scalar_type<int>()); ret["ele_type"] = Rcpp::String("logical"); } else ret["ele_type"] = Rcpp::String("unknown"); object_ref<dense_matrix> *ref = new object_ref<dense_matrix>(m); SEXP pointer = R_MakeExternalPtr(ref, R_NilValue, R_NilValue); R_RegisterCFinalizerEx(pointer, fm_clean_DM, TRUE); ret["pointer"] = pointer; Rcpp::NumericVector nrow(1); nrow[0] = m->get_num_rows(); ret["nrow"] = nrow; Rcpp::NumericVector ncol(1); ncol[0] = m->get_num_cols(); ret["ncol"] = ncol; return ret; } SEXP create_FMR_vector(detail::vec_store::const_ptr vec, const std::string &name) { detail::matrix_store::const_ptr mat = vec->conv2mat(vec->get_length(), 1, false); return create_FMR_vector(dense_matrix::create( detail::mem_matrix_store::cast(mat)), name); } SEXP create_FMR_vector(dense_matrix::ptr m, const std::string &name) { if (m->get_num_cols() > 1) m = m->transpose(); if (m->get_num_cols() > 1) { fprintf(stderr, "can't create a vector with a matrix with more than one col\n"); return R_NilValue; } Rcpp::List ret; ret["name"] = Rcpp::String(name); ret["type"] = Rcpp::String("vector"); if (m->is_type<int>()) ret["ele_type"] = Rcpp::String("integer"); else if (m->is_type<double>()) ret["ele_type"] = Rcpp::String("double"); else if (m->is_type<bool>()) { m = m->cast_ele_type(get_scalar_type<int>()); ret["ele_type"] = Rcpp::String("logical"); } else ret["ele_type"] = Rcpp::String("unknown"); object_ref<dense_matrix> *ref = new object_ref<dense_matrix>(m); SEXP pointer = R_MakeExternalPtr(ref, R_NilValue, R_NilValue); R_RegisterCFinalizerEx(pointer, fm_clean_DM, TRUE); ret["pointer"] = pointer; Rcpp::NumericVector len(1); len[0] = m->get_num_rows(); ret["len"] = len; return ret; } factor_col_vector::ptr get_factor_vector(const Rcpp::S4 &vec) { if (!is_factor_vector(vec)) { fprintf(stderr, "The S4 object isn't a factor vector\n"); return factor_col_vector::ptr(); } object_ref<dense_matrix> *ref = (object_ref<dense_matrix> *) R_ExternalPtrAddr(vec.slot("pointer")); dense_matrix::ptr mat = ref->get_object(); // This should be a column matrix. assert(mat->get_num_cols() == 1); size_t num_levels = vec.slot("num.levels"); return factor_col_vector::create(factor(num_levels), mat); } col_vec::ptr get_vector(const Rcpp::S4 &vec) { dense_matrix::ptr mat = get_matrix<dense_matrix>(vec); if (mat->get_num_rows() > 1 && mat->get_num_cols() > 1) { fprintf(stderr, "The input object is a matrix"); return col_vec::ptr(); } return col_vec::create(mat); } SEXP create_FMR_data_frame(data_frame::ptr df, const std::string &name) { Rcpp::List ret; for (size_t i = 0; i < df->get_num_vecs(); i++) { std::string vec_name = df->get_vec_name(i); ret[vec_name] = create_FMR_vector(df->get_vec(i), vec_name); } return ret; } <|endoftext|>
<commit_before>/* * Copyright (c) 2013 Chun-Ying Huang * * This file is part of GamingAnywhere (GA). * * GA is free software; you can redistribute it and/or modify it * under the terms of the 3-clause BSD License as published by the * Free Software Foundation: http://directory.fsf.org/wiki/License:BSD_3Clause * * GA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the 3-clause BSD License along with GA; * if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <stdio.h> #include <stdlib.h> #ifndef WIN32 #include <unistd.h> #endif #include "ga-common.h" #include "ga-conf.h" #include "ga-module.h" #include "rtspconf.h" #include "controller.h" #include "encoder-common.h" #define TEST_RECONFIGURE // image source pipeline: // vsource -- [vsource-%d] --> filter -- [filter-%d] --> encoder // configurations: static char *imagepipefmt = "video-%d"; static char *filterpipefmt = "filter-%d"; static char *imagepipe0 = "video-0"; static char *filterpipe0 = "filter-0"; static char *filter_param[] = { imagepipefmt, filterpipefmt }; static char *video_encoder_param = filterpipefmt; static void *audio_encoder_param = NULL; static struct gaRect *prect = NULL; static struct gaRect rect; static ga_module_t *m_vsource, *m_filter, *m_vencoder, *m_asource, *m_aencoder, *m_ctrl, *m_server; int load_modules() { if((m_vsource = ga_load_module("mod/vsource-desktop", "vsource_")) == NULL) return -1; if((m_filter = ga_load_module("mod/filter-rgb2yuv", "filter_RGB2YUV_")) == NULL) return -1; if((m_vencoder = ga_load_module("mod/encoder-video", "vencoder_")) == NULL) return -1; if(ga_conf_readbool("enable-audio", 1) != 0) { ////////////////////////// #ifndef __APPLE__ if((m_asource = ga_load_module("mod/asource-system", "asource_")) == NULL) return -1; #endif if((m_aencoder = ga_load_module("mod/encoder-audio", "aencoder_")) == NULL) return -1; ////////////////////////// } if((m_ctrl = ga_load_module("mod/ctrl-sdl", "sdlmsg_replay_")) == NULL) return -1; if((m_server = ga_load_module("mod/server-live555", "live_")) == NULL) return -1; return 0; } int init_modules() { struct RTSPConf *conf = rtspconf_global(); //static const char *filterpipe[] = { imagepipe0, filterpipe0 }; if(conf->ctrlenable) { ga_init_single_module_or_quit("controller", m_ctrl, (void *) prect); } // controller server is built-in - no need to init // note the order of the two modules ... ga_init_single_module_or_quit("video-source", m_vsource, (void*) prect); ga_init_single_module_or_quit("filter", m_filter, (void*) filter_param); // ga_init_single_module_or_quit("video-encoder", m_vencoder, filterpipefmt); if(ga_conf_readbool("enable-audio", 1) != 0) { ////////////////////////// #ifndef __APPLE__ ga_init_single_module_or_quit("audio-source", m_asource, NULL); #endif ga_init_single_module_or_quit("audio-encoder", m_aencoder, NULL); ////////////////////////// } // ga_init_single_module_or_quit("server-live555", m_server, NULL); // return 0; } int run_modules() { struct RTSPConf *conf = rtspconf_global(); static const char *filterpipe[] = { imagepipe0, filterpipe0 }; // controller server is built-in, but replay is a module if(conf->ctrlenable) { ga_run_single_module_or_quit("control server", ctrl_server_thread, conf); // XXX: safe to comment out? //ga_run_single_module_or_quit("control replayer", m_ctrl->threadproc, conf); } // video //ga_run_single_module_or_quit("image source", m_vsource->threadproc, (void*) imagepipefmt); if(m_vsource->start(prect) < 0) exit(-1); //ga_run_single_module_or_quit("filter 0", m_filter->threadproc, (void*) filterpipe); if(m_filter->start(filter_param) < 0) exit(-1); encoder_register_vencoder(m_vencoder, video_encoder_param); // audio if(ga_conf_readbool("enable-audio", 1) != 0) { ////////////////////////// #ifndef __APPLE__ //ga_run_single_module_or_quit("audio source", m_asource->threadproc, NULL); if(m_asource->start(NULL) < 0) exit(-1); #endif encoder_register_aencoder(m_aencoder, audio_encoder_param); ////////////////////////// } // server if(m_server->start(NULL) < 0) exit(-1); // return 0; } #ifdef TEST_RECONFIGURE static void * test_reconfig(void *) { int s = 0, err; int kbitrate[] = { 3000, 100 }; int framerate[][2] = { { 12, 1 }, {30, 1}, {24, 1} }; ga_error("reconfigure thread started ...\n"); while(1) { ga_ioctl_reconfigure_t reconf; if(encoder_running() == 0) { #ifdef WIN32 Sleep(1); #else sleep(1); #endif continue; } #ifdef WIN32 Sleep(20 * 1000); #else sleep(3); #endif bzero(&reconf, sizeof(reconf)); reconf.id = 0; reconf.bitrateKbps = kbitrate[s%2]; #if 0 reconf.bufsize = 5 * kbitrate[s%2] / 24; #endif // reconf.framerate_n = framerate[s%3][0]; // reconf.framerate_d = framerate[s%3][1]; // vsource /* if(m_vsource->ioctl) { err = m_vsource->ioctl(GA_IOCTL_RECONFIGURE, sizeof(reconf), &reconf); if(err < 0) { ga_error("reconfigure vsource failed, err = %d.\n", err); } else { ga_error("reconfigure vsource OK, framerate=%d/%d.\n", reconf.framerate_n, reconf.framerate_d); } } */ // encoder if(m_vencoder->ioctl) { err = m_vencoder->ioctl(GA_IOCTL_RECONFIGURE, sizeof(reconf), &reconf); if(err < 0) { ga_error("reconfigure encoder failed, err = %d.\n", err); } else { ga_error("reconfigure encoder OK, bitrate=%d; bufsize=%d; framerate=%d/%d.\n", reconf.bitrateKbps, reconf.bufsize, reconf.framerate_n, reconf.framerate_d); } } s = (s + 1) % 6; } return NULL; } #endif void handle_netreport(ctrlmsg_system_t *msg) { ctrlmsg_system_netreport_t *msgn = (ctrlmsg_system_netreport_t*) msg; ga_error("net-report: capacity=%.3f Kbps; loss-rate=%.2f%% (%u/%u); overhead=%.2f [%u KB received in %.3fs (%.2fKB/s)]\n", msgn->capacity / 1024.0, 100.0 * msgn->pktloss / msgn->pktcount, msgn->pktloss, msgn->pktcount, 1.0 * msgn->pktcount / msgn->framecount, msgn->bytecount / 1024, msgn->duration / 1000000.0, msgn->bytecount / 1024.0 / (msgn->duration / 1000000.0)); return; } int main(int argc, char *argv[]) { int notRunning = 0; #ifdef WIN32 if(CoInitializeEx(NULL, COINIT_MULTITHREADED) < 0) { fprintf(stderr, "cannot initialize COM.\n"); return -1; } #endif // if(argc < 2) { fprintf(stderr, "usage: %s config-file\n", argv[0]); return -1; } // if(ga_init(argv[1], NULL) < 0) { return -1; } // ga_openlog(); // if(rtspconf_parse(rtspconf_global()) < 0) { return -1; } // prect = NULL; // if(ga_crop_window(&rect, &prect) < 0) { return -1; } else if(prect == NULL) { ga_error("*** Crop disabled.\n"); } else if(prect != NULL) { ga_error("*** Crop enabled: (%d,%d)-(%d,%d)\n", prect->left, prect->top, prect->right, prect->bottom); } // if(load_modules() < 0) { return -1; } if(init_modules() < 0) { return -1; } if(run_modules() < 0) { return -1; } // enable handler to monitored network status ctrlsys_set_handler(CTRL_MSGSYS_SUBTYPE_NETREPORT, handle_netreport); // #ifdef TEST_RECONFIGURE pthread_t t; pthread_create(&t, NULL, test_reconfig, NULL); #endif //rtspserver_main(NULL); //liveserver_main(NULL); while(1) { usleep(5000000); } // alternatively, it is able to create a thread to run rtspserver_main: // pthread_create(&t, NULL, rtspserver_main, NULL); // ga_deinit(); // return 0; } <commit_msg>disable reconfiguration testing code<commit_after>/* * Copyright (c) 2013 Chun-Ying Huang * * This file is part of GamingAnywhere (GA). * * GA is free software; you can redistribute it and/or modify it * under the terms of the 3-clause BSD License as published by the * Free Software Foundation: http://directory.fsf.org/wiki/License:BSD_3Clause * * GA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the 3-clause BSD License along with GA; * if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <stdio.h> #include <stdlib.h> #ifndef WIN32 #include <unistd.h> #endif #include "ga-common.h" #include "ga-conf.h" #include "ga-module.h" #include "rtspconf.h" #include "controller.h" #include "encoder-common.h" //#define TEST_RECONFIGURE // image source pipeline: // vsource -- [vsource-%d] --> filter -- [filter-%d] --> encoder // configurations: static char *imagepipefmt = "video-%d"; static char *filterpipefmt = "filter-%d"; static char *imagepipe0 = "video-0"; static char *filterpipe0 = "filter-0"; static char *filter_param[] = { imagepipefmt, filterpipefmt }; static char *video_encoder_param = filterpipefmt; static void *audio_encoder_param = NULL; static struct gaRect *prect = NULL; static struct gaRect rect; static ga_module_t *m_vsource, *m_filter, *m_vencoder, *m_asource, *m_aencoder, *m_ctrl, *m_server; int load_modules() { if((m_vsource = ga_load_module("mod/vsource-desktop", "vsource_")) == NULL) return -1; if((m_filter = ga_load_module("mod/filter-rgb2yuv", "filter_RGB2YUV_")) == NULL) return -1; if((m_vencoder = ga_load_module("mod/encoder-video", "vencoder_")) == NULL) return -1; if(ga_conf_readbool("enable-audio", 1) != 0) { ////////////////////////// #ifndef __APPLE__ if((m_asource = ga_load_module("mod/asource-system", "asource_")) == NULL) return -1; #endif if((m_aencoder = ga_load_module("mod/encoder-audio", "aencoder_")) == NULL) return -1; ////////////////////////// } if((m_ctrl = ga_load_module("mod/ctrl-sdl", "sdlmsg_replay_")) == NULL) return -1; if((m_server = ga_load_module("mod/server-live555", "live_")) == NULL) return -1; return 0; } int init_modules() { struct RTSPConf *conf = rtspconf_global(); //static const char *filterpipe[] = { imagepipe0, filterpipe0 }; if(conf->ctrlenable) { ga_init_single_module_or_quit("controller", m_ctrl, (void *) prect); } // controller server is built-in - no need to init // note the order of the two modules ... ga_init_single_module_or_quit("video-source", m_vsource, (void*) prect); ga_init_single_module_or_quit("filter", m_filter, (void*) filter_param); // ga_init_single_module_or_quit("video-encoder", m_vencoder, filterpipefmt); if(ga_conf_readbool("enable-audio", 1) != 0) { ////////////////////////// #ifndef __APPLE__ ga_init_single_module_or_quit("audio-source", m_asource, NULL); #endif ga_init_single_module_or_quit("audio-encoder", m_aencoder, NULL); ////////////////////////// } // ga_init_single_module_or_quit("server-live555", m_server, NULL); // return 0; } int run_modules() { struct RTSPConf *conf = rtspconf_global(); static const char *filterpipe[] = { imagepipe0, filterpipe0 }; // controller server is built-in, but replay is a module if(conf->ctrlenable) { ga_run_single_module_or_quit("control server", ctrl_server_thread, conf); // XXX: safe to comment out? //ga_run_single_module_or_quit("control replayer", m_ctrl->threadproc, conf); } // video //ga_run_single_module_or_quit("image source", m_vsource->threadproc, (void*) imagepipefmt); if(m_vsource->start(prect) < 0) exit(-1); //ga_run_single_module_or_quit("filter 0", m_filter->threadproc, (void*) filterpipe); if(m_filter->start(filter_param) < 0) exit(-1); encoder_register_vencoder(m_vencoder, video_encoder_param); // audio if(ga_conf_readbool("enable-audio", 1) != 0) { ////////////////////////// #ifndef __APPLE__ //ga_run_single_module_or_quit("audio source", m_asource->threadproc, NULL); if(m_asource->start(NULL) < 0) exit(-1); #endif encoder_register_aencoder(m_aencoder, audio_encoder_param); ////////////////////////// } // server if(m_server->start(NULL) < 0) exit(-1); // return 0; } #ifdef TEST_RECONFIGURE static void * test_reconfig(void *) { int s = 0, err; int kbitrate[] = { 3000, 100 }; int framerate[][2] = { { 12, 1 }, {30, 1}, {24, 1} }; ga_error("reconfigure thread started ...\n"); while(1) { ga_ioctl_reconfigure_t reconf; if(encoder_running() == 0) { #ifdef WIN32 Sleep(1); #else sleep(1); #endif continue; } #ifdef WIN32 Sleep(20 * 1000); #else sleep(3); #endif bzero(&reconf, sizeof(reconf)); reconf.id = 0; reconf.bitrateKbps = kbitrate[s%2]; #if 0 reconf.bufsize = 5 * kbitrate[s%2] / 24; #endif // reconf.framerate_n = framerate[s%3][0]; // reconf.framerate_d = framerate[s%3][1]; // vsource /* if(m_vsource->ioctl) { err = m_vsource->ioctl(GA_IOCTL_RECONFIGURE, sizeof(reconf), &reconf); if(err < 0) { ga_error("reconfigure vsource failed, err = %d.\n", err); } else { ga_error("reconfigure vsource OK, framerate=%d/%d.\n", reconf.framerate_n, reconf.framerate_d); } } */ // encoder if(m_vencoder->ioctl) { err = m_vencoder->ioctl(GA_IOCTL_RECONFIGURE, sizeof(reconf), &reconf); if(err < 0) { ga_error("reconfigure encoder failed, err = %d.\n", err); } else { ga_error("reconfigure encoder OK, bitrate=%d; bufsize=%d; framerate=%d/%d.\n", reconf.bitrateKbps, reconf.bufsize, reconf.framerate_n, reconf.framerate_d); } } s = (s + 1) % 6; } return NULL; } #endif void handle_netreport(ctrlmsg_system_t *msg) { ctrlmsg_system_netreport_t *msgn = (ctrlmsg_system_netreport_t*) msg; ga_error("net-report: capacity=%.3f Kbps; loss-rate=%.2f%% (%u/%u); overhead=%.2f [%u KB received in %.3fs (%.2fKB/s)]\n", msgn->capacity / 1024.0, 100.0 * msgn->pktloss / msgn->pktcount, msgn->pktloss, msgn->pktcount, 1.0 * msgn->pktcount / msgn->framecount, msgn->bytecount / 1024, msgn->duration / 1000000.0, msgn->bytecount / 1024.0 / (msgn->duration / 1000000.0)); return; } int main(int argc, char *argv[]) { int notRunning = 0; #ifdef WIN32 if(CoInitializeEx(NULL, COINIT_MULTITHREADED) < 0) { fprintf(stderr, "cannot initialize COM.\n"); return -1; } #endif // if(argc < 2) { fprintf(stderr, "usage: %s config-file\n", argv[0]); return -1; } // if(ga_init(argv[1], NULL) < 0) { return -1; } // ga_openlog(); // if(rtspconf_parse(rtspconf_global()) < 0) { return -1; } // prect = NULL; // if(ga_crop_window(&rect, &prect) < 0) { return -1; } else if(prect == NULL) { ga_error("*** Crop disabled.\n"); } else if(prect != NULL) { ga_error("*** Crop enabled: (%d,%d)-(%d,%d)\n", prect->left, prect->top, prect->right, prect->bottom); } // if(load_modules() < 0) { return -1; } if(init_modules() < 0) { return -1; } if(run_modules() < 0) { return -1; } // enable handler to monitored network status ctrlsys_set_handler(CTRL_MSGSYS_SUBTYPE_NETREPORT, handle_netreport); // #ifdef TEST_RECONFIGURE pthread_t t; pthread_create(&t, NULL, test_reconfig, NULL); #endif //rtspserver_main(NULL); //liveserver_main(NULL); while(1) { usleep(5000000); } // alternatively, it is able to create a thread to run rtspserver_main: // pthread_create(&t, NULL, rtspserver_main, NULL); // ga_deinit(); // return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef IOX_UTILS_POSIX_WRAPPER_TIMER_HPP #define IOX_UTILS_POSIX_WRAPPER_TIMER_HPP #include "iceoryx_utils/cxx/optional.hpp" #include "iceoryx_utils/cxx/vector.hpp" #include "iceoryx_utils/design_pattern/creation.hpp" #include "iceoryx_utils/internal/units/duration.hpp" #include "iceoryx_utils/platform/signal.hpp" #include "iceoryx_utils/platform/time.hpp" #include <atomic> #include <condition_variable> #include <cstdint> #include <ctime> #include <functional> #include <limits> namespace iox { namespace posix { enum class TimerError { NO_ERROR, TIMER_NOT_INITIALIZED, NO_VALID_CALLBACK, KERNEL_ALLOC_FAILED, INVALID_ARGUMENTS, ALLOC_MEM_FAILED, NO_PERMISSION, INVALID_POINTER, NO_TIMER_TO_DELETE, TIMEOUT_IS_ZERO, INTERNAL_LOGIC_ERROR }; using namespace iox::units::duration_literals; /// @brief Interface for timers on POSIX operating systems /// @note Can't be copied or moved as operating system has a pointer to this object. It needs to be ensured that this /// object lives longer than timeToWait, otherwise the operating system will unregister the timer /// @concurrent not thread safe /// /// @code /// posix::Timer TiborTheTimer{100_ms, [&]() { fooBar++; }}; /// /// // Start a periodic timer /// TiborTheTimer.start(true); /// // [.. wait ..] /// // Timer fires after 100_ms and calls the lambda which increments fooBar /// /// TiborTheTimer.stop(); /// /// @endcode class Timer { public: enum class RunMode { ONCE, PERIODIC }; /// @brief /// when the callback is still running when the callback should be retriggered: /// - SOFT_TIMER = do nothing /// - ASAP_TIMER = retrigger callback right after the callback is finished /// - HARD_TIMER = terminate enum class TimerType { SOFT_TIMER, ASAP_TIMER, HARD_TIMER }; private: static constexpr size_t SIZE_OF_COMBINDED_INDEX_AND_DESCRIPTOR = sizeof(uint32_t); static constexpr size_t SIZE_OF_SIGVAL_INT = sizeof(int); static_assert(SIZE_OF_SIGVAL_INT >= SIZE_OF_COMBINDED_INDEX_AND_DESCRIPTOR, "size of sigval_int is to low"); static constexpr uint32_t MAX_NUMBER_OF_CALLBACK_HANDLES = 100u; static_assert(MAX_NUMBER_OF_CALLBACK_HANDLES <= std::numeric_limits<uint8_t>::max(), "number of callback handles exceeds max index value"); class OsTimer; struct OsTimerCallbackHandle { static constexpr uint32_t MAX_DESCRIPTOR_VALUE{(1u << 24u) - 1u}; static sigval indexAndDescriptorToSigval(uint8_t index, uint32_t descriptor) noexcept; static uint8_t sigvalToIndex(sigval intVal) noexcept; static uint32_t sigvalToDescriptor(sigval intVal) noexcept; void incrementDescriptor() noexcept; std::mutex m_accessMutex; /// @brief the descriptor is unique for a timer_t in OsTimer, if this handle is recycled, the descriptor needs /// to be incremented first std::atomic<uint32_t> m_descriptor{0u}; std::atomic<bool> m_inUse{false}; std::atomic<bool> m_isTimerActive{false}; std::atomic<uint64_t> m_cycle{0u}; TimerType m_timerType{TimerType::HARD_TIMER}; OsTimer* m_timer{nullptr}; }; class OsTimer { #ifdef __QNX__ static constexpr timer_t INVALID_TIMER_ID = 0; #else static constexpr timer_t INVALID_TIMER_ID = nullptr; #endif public: /// @brief Wrapper that can be registered with the operating system static void callbackHelper(sigval data); OsTimer(const units::Duration timeToWait, const std::function<void()>& callback) noexcept; OsTimer(const OsTimer&) = delete; OsTimer(OsTimer&&) = delete; OsTimer& operator=(const OsTimer&) = delete; OsTimer& operator=(OsTimer&&) = delete; /// @brief D'tor virtual ~OsTimer() noexcept; /// @brief Starts the timer /// /// The callback is called by the operating system after the time has expired. /// /// @param[in] periodic - can be a periodic timer if set to RunMode::PERIODIC or /// once when in RunMode::ONCE /// @note Shall only be called when callback is given cxx::expected<TimerError> start(const RunMode runMode, const TimerType timerType) noexcept; /// @brief Disarms the timer /// @note Shall only be called when callback is given, guarantee after stop() call is callback is immediately /// called or never at all cxx::expected<TimerError> stop() noexcept; /// @brief Disarms the timer, assigns a new timeToWait value and arms the timer /// @note Shall only be called when callback is given cxx::expected<TimerError> restart(const units::Duration timeToWait, const RunMode runMode, const TimerType timerType) noexcept; // @brief Returns the time until the timer expires the next time /// @note Shall only be called when callback is given cxx::expected<units::Duration, TimerError> timeUntilExpiration() noexcept; /// @brief In case the callback is not immediately called by the operating system, getOverruns() returns the /// additional overruns that happended in the delay interval /// @note Shall only be called when callback is given cxx::expected<uint64_t, TimerError> getOverruns() noexcept; /// @brief Returns true if the construction of the object was successful bool hasError() const noexcept; /// @brief Returns the error that occured on constructing the object TimerError getError() const noexcept; private: /// @brief Call the user-defined callback /// @note This call is wrapped in a plain C function void executeCallback(const uint64_t currentCycle) noexcept; private: /// @brief Duration after the timer calls the user-defined callback function units::Duration m_timeToWait; /// @brief Stores the user-defined callback std::function<void()> m_callback; /// @brief Identifier for the timer in the operating system timer_t m_timerId{INVALID_TIMER_ID}; uint8_t m_callbackHandleIndex{0u}; /// @todo will be obsolete with creation pattern /// @brief Bool that signals whether the object is fully initalized bool m_isInitialized{false}; /// @todo creation pattern /// @brief If an error happened during creation the value is stored in here TimerError m_errorValue{TimerError::NO_ERROR}; static OsTimerCallbackHandle s_callbackHandlePool[MAX_NUMBER_OF_CALLBACK_HANDLES]; }; public: /// @brief Creates a timer without an operating system callback /// /// Creates a light-weight timer object that can be used with /// * hasExpiredComparedToCreationTime() /// * resetCreationTime() /// /// @param[in] timeToWait - How long should be waited? /// @note Does not set up an operating system timer, but uses CLOCK_REALTIME instead /// @todo refactor this cTor and its functionality to a class called StopWatch Timer(const units::Duration timeToWait) noexcept; /// @brief Creates a timer with an operating system callback /// /// Initially the timer is stopped. /// /// @param[in] timeToWait - How long should be waited? /// @param[in] callback - Function called after timeToWait (User needs to ensure lifetime of function till stop() /// call) /// @note Operating systems needs a valid reference to this object, hence DesignPattern::Creation can't be used Timer(const units::Duration timeToWait, const std::function<void()>& callback) noexcept; /// @brief creates Duration from the result of clock_gettime(CLOCK_REALTIME, ...) /// @return if the clock_gettime call failed TimerError is returned otherwise Duration /// @todo maybe move this to a clock implementation? static cxx::expected<units::Duration, TimerError> now() noexcept; /// @brief Move or semantics are forbidden as address of object is not allowed to change Timer(const Timer& other) = delete; /// @brief Move or semantics are forbidden as address of object is not allowed to change Timer(Timer&& other) = delete; /// @brief Move or semantics are forbidden as address of object is not allowed to change Timer& operator=(const Timer& other) = delete; /// @brief Move or semantics are forbidden as address of object is not allowed to change Timer& operator=(Timer&& other) = delete; /// @brief D'tor virtual ~Timer() noexcept = default; /// @brief Starts the timer /// /// The callback is called by the operating system after the time has expired. /// /// @param[in] periodic - can be a periodic timer if set to true, default false /// @note Shall only be called when callback is given /// @todo replace bool with enum; SingleShot and Periodic cxx::expected<TimerError> start(const RunMode runMode, const TimerType timerType) noexcept; /// @brief Disarms the timer /// @note Shall only be called when callback is given, guarantee after stop() call is callback is immediately /// called or never at all cxx::expected<TimerError> stop() noexcept; /// @brief Disarms the timer, assigns a new timeToWait value and arms the timer /// @note Shall only be called when callback is given cxx::expected<TimerError> restart(const units::Duration timeToWait, const RunMode runMode, const TimerType timerType) noexcept; /// @brief Resets the internal creation time void resetCreationTime() noexcept; /// @brief Checks if the timer has expired compared to its creation time /// @return Is the elapsed time larger than timeToWait? bool hasExpiredComparedToCreationTime() noexcept; // @brief Returns the time until the timer expires the next time /// @note Shall only be called when callback is given cxx::expected<units::Duration, TimerError> timeUntilExpiration() noexcept; /// @brief In case the callback is not immediately called by the operating system, getOverruns() returns the /// additional overruns that happended in the delay interval /// @note Shall only be called when callback is given cxx::expected<uint64_t, TimerError> getOverruns() noexcept; /// @brief Returns true if the construction of the object was successful bool hasError() const noexcept; /// @brief Returns the error that occured on constructing the object TimerError getError() const noexcept; private: cxx::optional<OsTimer> m_osTimer; /// @brief Converts errnum to TimerError static cxx::error<TimerError> createErrorFromErrno(const int32_t errnum) noexcept; /// @brief Duration after the timer calls the user-defined callback function units::Duration m_timeToWait; /// @brief Time when the timer object was created units::Duration m_creationTime; /// @brief If an error happened during creation the value is stored in here TimerError m_errorValue{TimerError::NO_ERROR}; }; } // namespace posix } // namespace iox #endif // IOX_UTILS_POSIX_WRAPPER_TIMER_HPP <commit_msg>iox-#167: updated doxygen docu<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef IOX_UTILS_POSIX_WRAPPER_TIMER_HPP #define IOX_UTILS_POSIX_WRAPPER_TIMER_HPP #include "iceoryx_utils/cxx/optional.hpp" #include "iceoryx_utils/cxx/vector.hpp" #include "iceoryx_utils/design_pattern/creation.hpp" #include "iceoryx_utils/internal/units/duration.hpp" #include "iceoryx_utils/platform/signal.hpp" #include "iceoryx_utils/platform/time.hpp" #include <atomic> #include <condition_variable> #include <cstdint> #include <ctime> #include <functional> #include <limits> namespace iox { namespace posix { enum class TimerError { NO_ERROR, TIMER_NOT_INITIALIZED, NO_VALID_CALLBACK, KERNEL_ALLOC_FAILED, INVALID_ARGUMENTS, ALLOC_MEM_FAILED, NO_PERMISSION, INVALID_POINTER, NO_TIMER_TO_DELETE, TIMEOUT_IS_ZERO, INTERNAL_LOGIC_ERROR }; using namespace iox::units::duration_literals; /// @brief Interface for timers on POSIX operating systems /// @note Can't be copied or moved as operating system has a pointer to this object. It needs to be ensured that this /// object lives longer than timeToWait, otherwise the operating system will unregister the timer /// @concurrent not thread safe /// /// @code /// posix::Timer TiborTheTimer{100_ms, [&]() { fooBar++; }}; /// /// // Start a periodic timer /// TiborTheTimer.start(true); /// // [.. wait ..] /// // Timer fires after 100_ms and calls the lambda which increments fooBar /// /// TiborTheTimer.stop(); /// /// @endcode class Timer { public: enum class RunMode { ONCE, PERIODIC }; /// @brief /// when the callback is still running when the callback should be retriggered: /// - SOFT_TIMER = do nothing /// - ASAP_TIMER = retrigger callback right after the callback is finished /// - HARD_TIMER = terminate enum class TimerType { SOFT_TIMER, ASAP_TIMER, HARD_TIMER }; private: static constexpr size_t SIZE_OF_COMBINDED_INDEX_AND_DESCRIPTOR = sizeof(uint32_t); static constexpr size_t SIZE_OF_SIGVAL_INT = sizeof(int); static_assert(SIZE_OF_SIGVAL_INT >= SIZE_OF_COMBINDED_INDEX_AND_DESCRIPTOR, "size of sigval_int is to low"); static constexpr uint32_t MAX_NUMBER_OF_CALLBACK_HANDLES = 100u; static_assert(MAX_NUMBER_OF_CALLBACK_HANDLES <= std::numeric_limits<uint8_t>::max(), "number of callback handles exceeds max index value"); class OsTimer; struct OsTimerCallbackHandle { static constexpr uint32_t MAX_DESCRIPTOR_VALUE{(1u << 24u) - 1u}; static sigval indexAndDescriptorToSigval(uint8_t index, uint32_t descriptor) noexcept; static uint8_t sigvalToIndex(sigval intVal) noexcept; static uint32_t sigvalToDescriptor(sigval intVal) noexcept; void incrementDescriptor() noexcept; std::mutex m_accessMutex; /// @brief the descriptor is unique for a timer_t in OsTimer, if this handle is recycled, the descriptor needs /// to be incremented first std::atomic<uint32_t> m_descriptor{0u}; std::atomic<bool> m_inUse{false}; std::atomic<bool> m_isTimerActive{false}; std::atomic<uint64_t> m_cycle{0u}; TimerType m_timerType{TimerType::HARD_TIMER}; OsTimer* m_timer{nullptr}; }; class OsTimer { #ifdef __QNX__ static constexpr timer_t INVALID_TIMER_ID = 0; #else static constexpr timer_t INVALID_TIMER_ID = nullptr; #endif public: /// @brief Wrapper that can be registered with the operating system static void callbackHelper(sigval data); OsTimer(const units::Duration timeToWait, const std::function<void()>& callback) noexcept; OsTimer(const OsTimer&) = delete; OsTimer(OsTimer&&) = delete; OsTimer& operator=(const OsTimer&) = delete; OsTimer& operator=(OsTimer&&) = delete; /// @brief D'tor virtual ~OsTimer() noexcept; /// @brief Starts the timer /// /// The callback is called by the operating system after the time has expired. /// /// @param[in] periodic - can be a periodic timer if set to RunMode::PERIODIC or /// once when in RunMode::ONCE /// @note Shall only be called when callback is given cxx::expected<TimerError> start(const RunMode runMode, const TimerType timerType) noexcept; /// @brief Disarms the timer /// @note Shall only be called when callback is given, guarantee after stop() call is callback is immediately /// called or never at all cxx::expected<TimerError> stop() noexcept; /// @brief Disarms the timer, assigns a new timeToWait value and arms the timer /// @note Shall only be called when callback is given cxx::expected<TimerError> restart(const units::Duration timeToWait, const RunMode runMode, const TimerType timerType) noexcept; // @brief Returns the time until the timer expires the next time /// @note Shall only be called when callback is given cxx::expected<units::Duration, TimerError> timeUntilExpiration() noexcept; /// @brief In case the callback is not immediately called by the operating system, getOverruns() returns the /// additional overruns that happended in the delay interval /// @note Shall only be called when callback is given cxx::expected<uint64_t, TimerError> getOverruns() noexcept; /// @brief Returns true if the construction of the object was successful bool hasError() const noexcept; /// @brief Returns the error that occured on constructing the object TimerError getError() const noexcept; private: /// @brief Call the user-defined callback /// @note This call is wrapped in a plain C function void executeCallback(const uint64_t currentCycle) noexcept; private: /// @brief Duration after the timer calls the user-defined callback function units::Duration m_timeToWait; /// @brief Stores the user-defined callback std::function<void()> m_callback; /// @brief Identifier for the timer in the operating system timer_t m_timerId{INVALID_TIMER_ID}; uint8_t m_callbackHandleIndex{0u}; /// @todo will be obsolete with creation pattern /// @brief Bool that signals whether the object is fully initalized bool m_isInitialized{false}; /// @todo creation pattern /// @brief If an error happened during creation the value is stored in here TimerError m_errorValue{TimerError::NO_ERROR}; static OsTimerCallbackHandle s_callbackHandlePool[MAX_NUMBER_OF_CALLBACK_HANDLES]; }; public: /// @brief Creates a timer without an operating system callback /// /// Creates a light-weight timer object that can be used with /// * hasExpiredComparedToCreationTime() /// * resetCreationTime() /// /// @param[in] timeToWait - How long should be waited? /// @note Does not set up an operating system timer, but uses CLOCK_REALTIME instead /// @todo refactor this cTor and its functionality to a class called StopWatch Timer(const units::Duration timeToWait) noexcept; /// @brief Creates a timer with an operating system callback /// /// Initially the timer is stopped. /// /// @param[in] timeToWait - How long should be waited? /// @param[in] callback - Function called after timeToWait (User needs to ensure lifetime of function till stop() /// call) /// @note Operating systems needs a valid reference to this object, hence DesignPattern::Creation can't be used Timer(const units::Duration timeToWait, const std::function<void()>& callback) noexcept; /// @brief creates Duration from the result of clock_gettime(CLOCK_REALTIME, ...) /// @return if the clock_gettime call failed TimerError is returned otherwise Duration /// @todo maybe move this to a clock implementation? static cxx::expected<units::Duration, TimerError> now() noexcept; /// @brief Move or semantics are forbidden as address of object is not allowed to change Timer(const Timer& other) = delete; /// @brief Move or semantics are forbidden as address of object is not allowed to change Timer(Timer&& other) = delete; /// @brief Move or semantics are forbidden as address of object is not allowed to change Timer& operator=(const Timer& other) = delete; /// @brief Move or semantics are forbidden as address of object is not allowed to change Timer& operator=(Timer&& other) = delete; /// @brief D'tor virtual ~Timer() noexcept = default; /// @brief Starts the timer /// /// The callback is called by the operating system after the time has expired. /// /// @param[in] runMode for continuous callbacks PERIODIC otherwise ONCE /// @param[in] TimerType selects the timer behavior /// @note Shall only be called when callback is given cxx::expected<TimerError> start(const RunMode runMode, const TimerType timerType) noexcept; /// @brief Disarms the timer /// @note Shall only be called when callback is given, guarantee after stop() call is callback is immediately /// called or never at all cxx::expected<TimerError> stop() noexcept; /// @brief Disarms the timer, assigns a new timeToWait value and arms the timer /// @param[in] timeToWait duration till the callback should be called /// @param[in] runMode for continuous callbacks PERIODIC otherwise ONCE /// @param[in] TimerType selects the timer behavior /// @note Shall only be called when callback is given cxx::expected<TimerError> restart(const units::Duration timeToWait, const RunMode runMode, const TimerType timerType) noexcept; /// @brief Resets the internal creation time void resetCreationTime() noexcept; /// @brief Checks if the timer has expired compared to its creation time /// @return Is the elapsed time larger than timeToWait? bool hasExpiredComparedToCreationTime() noexcept; // @brief Returns the time until the timer expires the next time /// @note Shall only be called when callback is given cxx::expected<units::Duration, TimerError> timeUntilExpiration() noexcept; /// @brief In case the callback is not immediately called by the operating system, getOverruns() returns the /// additional overruns that happended in the delay interval /// @note Shall only be called when callback is given cxx::expected<uint64_t, TimerError> getOverruns() noexcept; /// @brief Returns true if the construction of the object was successful bool hasError() const noexcept; /// @brief Returns the error that occured on constructing the object TimerError getError() const noexcept; private: cxx::optional<OsTimer> m_osTimer; /// @brief Converts errnum to TimerError static cxx::error<TimerError> createErrorFromErrno(const int32_t errnum) noexcept; /// @brief Duration after the timer calls the user-defined callback function units::Duration m_timeToWait; /// @brief Time when the timer object was created units::Duration m_creationTime; /// @brief If an error happened during creation the value is stored in here TimerError m_errorValue{TimerError::NO_ERROR}; }; } // namespace posix } // namespace iox #endif // IOX_UTILS_POSIX_WRAPPER_TIMER_HPP <|endoftext|>
<commit_before> /* * Copyright (c) 1999-2008 Mark D. Hill and David A. Wood * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * $Id$ * */ #include "mem/ruby/tester/Check.hh" #include "mem/ruby/system/Sequencer.hh" #include "mem/ruby/system/System.hh" #include "mem/ruby/common/SubBlock.hh" #include "mem/protocol/Chip.hh" #include "mem/packet.hh" Check::Check(const Address& address, const Address& pc) { m_status = TesterStatus_Idle; pickValue(); pickInitiatingNode(); changeAddress(address); m_pc = pc; m_access_mode = AccessModeType(random() % AccessModeType_NUM); m_store_count = 0; } void Check::initiate() { DEBUG_MSG(TESTER_COMP, MedPrio, "initiating"); DEBUG_EXPR(TESTER_COMP, MedPrio, *this); // current CMP protocol doesn't support prefetches if (!Protocol::m_CMP && (random() & 0xf) == 0) { // 1 in 16 chance initiatePrefetch(); // Prefetch from random processor } if(m_status == TesterStatus_Idle) { initiateAction(); } else if(m_status == TesterStatus_Ready) { initiateCheck(); } else { // Pending - do nothing DEBUG_MSG(TESTER_COMP, MedPrio, "initiating action/check - failed: action/check is pending\n"); } } void Check::initiatePrefetch(Sequencer* targetSequencer_ptr) { DEBUG_MSG(TESTER_COMP, MedPrio, "initiating prefetch"); CacheRequestType type; if ((random() & 0x7) != 0) { // 1 in 8 chance if ((random() & 0x1) == 0) { // 50% chance type = CacheRequestType_LD; } else { type = CacheRequestType_IFETCH; } } else { type = CacheRequestType_ST; } Addr data_addr = m_address.getAddress(); Addr pc_addr = m_pc.getAddress(); Request request(0, data_addr, 0, Flags<unsigned int>(Request::PREFETCH), pc_addr, 0, 0); MemCmd::Command command; if (type == CacheRequestType_IFETCH) { command = MemCmd::ReadReq; request.setFlags(Request::INST_FETCH); } else if (type == CacheRequestType_LD || type == CacheRequestType_IFETCH) { command = MemCmd::ReadReq; } else if (type == CacheRequestType_ST) { command = MemCmd::WriteReq; } else if (type == CacheRequestType_ATOMIC) { command = MemCmd::SwapReq; // TODO -- differentiate between atomic types } else { assert(false); } Packet pkt(&request, command, 0); // TODO -- make dest a real NodeID assert(targetSequencer_ptr != NULL); if (targetSequencer_ptr->isReady(&pkt)) { targetSequencer_ptr->makeRequest(&pkt); } } void Check::initiatePrefetch() { // Any sequencer can issue a prefetch for this address Sequencer* targetSequencer_ptr = g_system_ptr->getChip(random() % RubyConfig::numberOfChips())->getSequencer(random() % RubyConfig::numberOfProcsPerChip()); assert(targetSequencer_ptr != NULL); initiatePrefetch(targetSequencer_ptr); } void Check::initiateAction() { DEBUG_MSG(TESTER_COMP, MedPrio, "initiating Action"); assert(m_status == TesterStatus_Idle); CacheRequestType type = CacheRequestType_ST; if ((random() & 0x1) == 0) { // 50% chance type = CacheRequestType_ATOMIC; } Addr data_addr = m_address.getAddress()+m_store_count; Addr pc_addr = m_pc.getAddress(); Request request(0, data_addr, 1, Flags<unsigned int>(), pc_addr, 0, 0); MemCmd::Command command; if (type == CacheRequestType_IFETCH) { command = MemCmd::ReadReq; request.setFlags(Request::INST_FETCH); } else if (type == CacheRequestType_LD || type == CacheRequestType_IFETCH) { command = MemCmd::ReadReq; } else if (type == CacheRequestType_ST) { command = MemCmd::WriteReq; } else if (type == CacheRequestType_ATOMIC) { command = MemCmd::SwapReq; // TODO -- differentiate between atomic types } else { assert(false); } Packet pkt(&request, command, 0); // TODO -- make dest a real NodeID Sequencer* sequencer_ptr = initiatingSequencer(); if (sequencer_ptr->isReady(&pkt) == false) { DEBUG_MSG(TESTER_COMP, MedPrio, "failed to initiate action - sequencer not ready\n"); } else { DEBUG_MSG(TESTER_COMP, MedPrio, "initiating action - successful\n"); DEBUG_EXPR(TESTER_COMP, MedPrio, m_status); m_status = TesterStatus_Action_Pending; sequencer_ptr->makeRequest(&pkt); } DEBUG_EXPR(TESTER_COMP, MedPrio, m_status); } void Check::initiateCheck() { DEBUG_MSG(TESTER_COMP, MedPrio, "initiating Check"); assert(m_status == TesterStatus_Ready); CacheRequestType type = CacheRequestType_LD; if ((random() & 0x1) == 0) { // 50% chance type = CacheRequestType_IFETCH; } Addr data_addr = m_address.getAddress()+m_store_count; Addr pc_addr = m_pc.getAddress(); Request request(0, data_addr, CHECK_SIZE, Flags<unsigned int>(), pc_addr, 0, 0); MemCmd::Command command; if (type == CacheRequestType_IFETCH) { command = MemCmd::ReadReq; request.setFlags(Request::INST_FETCH); } else if (type == CacheRequestType_LD || type == CacheRequestType_IFETCH) { command = MemCmd::ReadReq; } else if (type == CacheRequestType_ST) { command = MemCmd::WriteReq; } else if (type == CacheRequestType_ATOMIC) { command = MemCmd::SwapReq; // TODO -- differentiate between atomic types } else { assert(false); } Packet pkt(&request, command, 0); // TODO -- make dest a real NodeID Sequencer* sequencer_ptr = initiatingSequencer(); if (sequencer_ptr->isReady(&pkt) == false) { DEBUG_MSG(TESTER_COMP, MedPrio, "failed to initiate check - sequencer not ready\n"); } else { DEBUG_MSG(TESTER_COMP, MedPrio, "initiating check - successful\n"); DEBUG_MSG(TESTER_COMP, MedPrio, m_status); m_status = TesterStatus_Check_Pending; sequencer_ptr->makeRequest(&pkt); } DEBUG_MSG(TESTER_COMP, MedPrio, m_status); } void Check::performCallback(NodeID proc, SubBlock& data) { Address address = data.getAddress(); // assert(getAddress() == address); // This isn't exactly right since we now have multi-byte checks assert(getAddress().getLineAddress() == address.getLineAddress()); DEBUG_MSG(TESTER_COMP, MedPrio, "Callback"); DEBUG_EXPR(TESTER_COMP, MedPrio, *this); if (m_status == TesterStatus_Action_Pending) { DEBUG_MSG(TESTER_COMP, MedPrio, "Action callback"); // Perform store data.setByte(0, m_value+m_store_count); // We store one byte at a time m_store_count++; if (m_store_count == CHECK_SIZE) { m_status = TesterStatus_Ready; } else { m_status = TesterStatus_Idle; } } else if (m_status == TesterStatus_Check_Pending) { DEBUG_MSG(TESTER_COMP, MedPrio, "Check callback"); // Perform load/check for(int byte_number=0; byte_number<CHECK_SIZE; byte_number++) { if (uint8(m_value+byte_number) != data.getByte(byte_number) && (DATA_BLOCK == true)) { WARN_EXPR(proc); WARN_EXPR(address); WARN_EXPR(data); WARN_EXPR(byte_number); WARN_EXPR((int)m_value+byte_number); WARN_EXPR((int)data.getByte(byte_number)); WARN_EXPR(*this); WARN_EXPR(g_eventQueue_ptr->getTime()); ERROR_MSG("Action/check failure"); } } DEBUG_MSG(TESTER_COMP, HighPrio, "Action/check success:"); DEBUG_EXPR(TESTER_COMP, HighPrio, *this); DEBUG_EXPR(TESTER_COMP, MedPrio, data); m_status = TesterStatus_Idle; pickValue(); } else { WARN_EXPR(*this); WARN_EXPR(proc); WARN_EXPR(data); WARN_EXPR(m_status); WARN_EXPR(g_eventQueue_ptr->getTime()); ERROR_MSG("Unexpected TesterStatus"); } DEBUG_EXPR(TESTER_COMP, MedPrio, proc); DEBUG_EXPR(TESTER_COMP, MedPrio, data); DEBUG_EXPR(TESTER_COMP, MedPrio, getAddress().getLineAddress()); DEBUG_MSG(TESTER_COMP, MedPrio, "Callback done"); DEBUG_EXPR(TESTER_COMP, MedPrio, *this); } void Check::changeAddress(const Address& address) { assert((m_status == TesterStatus_Idle) || (m_status == TesterStatus_Ready)); m_status = TesterStatus_Idle; m_address = address; m_store_count = 0; } Sequencer* Check::initiatingSequencer() const { return g_system_ptr->getChip(m_initiatingNode/RubyConfig::numberOfProcsPerChip())->getSequencer(m_initiatingNode%RubyConfig::numberOfProcsPerChip()); } void Check::pickValue() { assert(m_status == TesterStatus_Idle); m_status = TesterStatus_Idle; // DEBUG_MSG(TESTER_COMP, MedPrio, m_status); DEBUG_MSG(TESTER_COMP, MedPrio, *this); m_value = random() & 0xff; // One byte // DEBUG_MSG(TESTER_COMP, MedPrio, m_value); DEBUG_MSG(TESTER_COMP, MedPrio, *this); m_store_count = 0; } void Check::pickInitiatingNode() { assert((m_status == TesterStatus_Idle) || (m_status == TesterStatus_Ready)); m_status = TesterStatus_Idle; DEBUG_MSG(TESTER_COMP, MedPrio, m_status); m_initiatingNode = (random() % RubyConfig::numberOfProcessors()); DEBUG_MSG(TESTER_COMP, MedPrio, m_initiatingNode); m_store_count = 0; } void Check::print(ostream& out) const { out << "[" << m_address << ", value: " << (int) m_value << ", status: " << m_status << ", initiating node: " << m_initiatingNode << ", store_count: " << m_store_count << "]" << flush; } <commit_msg>ruby: assert(false) should be panic. This also fixes some compiler warnings<commit_after> /* * Copyright (c) 1999-2008 Mark D. Hill and David A. Wood * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * $Id$ * */ #include "mem/ruby/tester/Check.hh" #include "mem/ruby/system/Sequencer.hh" #include "mem/ruby/system/System.hh" #include "mem/ruby/common/SubBlock.hh" #include "mem/protocol/Chip.hh" #include "mem/packet.hh" Check::Check(const Address& address, const Address& pc) { m_status = TesterStatus_Idle; pickValue(); pickInitiatingNode(); changeAddress(address); m_pc = pc; m_access_mode = AccessModeType(random() % AccessModeType_NUM); m_store_count = 0; } void Check::initiate() { DEBUG_MSG(TESTER_COMP, MedPrio, "initiating"); DEBUG_EXPR(TESTER_COMP, MedPrio, *this); // current CMP protocol doesn't support prefetches if (!Protocol::m_CMP && (random() & 0xf) == 0) { // 1 in 16 chance initiatePrefetch(); // Prefetch from random processor } if(m_status == TesterStatus_Idle) { initiateAction(); } else if(m_status == TesterStatus_Ready) { initiateCheck(); } else { // Pending - do nothing DEBUG_MSG(TESTER_COMP, MedPrio, "initiating action/check - failed: action/check is pending\n"); } } void Check::initiatePrefetch(Sequencer* targetSequencer_ptr) { DEBUG_MSG(TESTER_COMP, MedPrio, "initiating prefetch"); CacheRequestType type; if ((random() & 0x7) != 0) { // 1 in 8 chance if ((random() & 0x1) == 0) { // 50% chance type = CacheRequestType_LD; } else { type = CacheRequestType_IFETCH; } } else { type = CacheRequestType_ST; } Addr data_addr = m_address.getAddress(); Addr pc_addr = m_pc.getAddress(); Request request(0, data_addr, 0, Flags<unsigned int>(Request::PREFETCH), pc_addr, 0, 0); MemCmd::Command command; if (type == CacheRequestType_IFETCH) { command = MemCmd::ReadReq; request.setFlags(Request::INST_FETCH); } else if (type == CacheRequestType_LD || type == CacheRequestType_IFETCH) { command = MemCmd::ReadReq; } else if (type == CacheRequestType_ST) { command = MemCmd::WriteReq; } else if (type == CacheRequestType_ATOMIC) { command = MemCmd::SwapReq; // TODO -- differentiate between atomic types } else { panic("Cannot convert request to packet"); } Packet pkt(&request, command, 0); // TODO -- make dest a real NodeID assert(targetSequencer_ptr != NULL); if (targetSequencer_ptr->isReady(&pkt)) { targetSequencer_ptr->makeRequest(&pkt); } } void Check::initiatePrefetch() { // Any sequencer can issue a prefetch for this address Sequencer* targetSequencer_ptr = g_system_ptr->getChip(random() % RubyConfig::numberOfChips())->getSequencer(random() % RubyConfig::numberOfProcsPerChip()); assert(targetSequencer_ptr != NULL); initiatePrefetch(targetSequencer_ptr); } void Check::initiateAction() { DEBUG_MSG(TESTER_COMP, MedPrio, "initiating Action"); assert(m_status == TesterStatus_Idle); CacheRequestType type = CacheRequestType_ST; if ((random() & 0x1) == 0) { // 50% chance type = CacheRequestType_ATOMIC; } Addr data_addr = m_address.getAddress()+m_store_count; Addr pc_addr = m_pc.getAddress(); Request request(0, data_addr, 1, Flags<unsigned int>(), pc_addr, 0, 0); MemCmd::Command command; if (type == CacheRequestType_IFETCH) { command = MemCmd::ReadReq; request.setFlags(Request::INST_FETCH); } else if (type == CacheRequestType_LD || type == CacheRequestType_IFETCH) { command = MemCmd::ReadReq; } else if (type == CacheRequestType_ST) { command = MemCmd::WriteReq; } else if (type == CacheRequestType_ATOMIC) { command = MemCmd::SwapReq; // TODO -- differentiate between atomic types } else { panic("Cannot convert request to packet"); } Packet pkt(&request, command, 0); // TODO -- make dest a real NodeID Sequencer* sequencer_ptr = initiatingSequencer(); if (sequencer_ptr->isReady(&pkt) == false) { DEBUG_MSG(TESTER_COMP, MedPrio, "failed to initiate action - sequencer not ready\n"); } else { DEBUG_MSG(TESTER_COMP, MedPrio, "initiating action - successful\n"); DEBUG_EXPR(TESTER_COMP, MedPrio, m_status); m_status = TesterStatus_Action_Pending; sequencer_ptr->makeRequest(&pkt); } DEBUG_EXPR(TESTER_COMP, MedPrio, m_status); } void Check::initiateCheck() { DEBUG_MSG(TESTER_COMP, MedPrio, "initiating Check"); assert(m_status == TesterStatus_Ready); CacheRequestType type = CacheRequestType_LD; if ((random() & 0x1) == 0) { // 50% chance type = CacheRequestType_IFETCH; } Addr data_addr = m_address.getAddress()+m_store_count; Addr pc_addr = m_pc.getAddress(); Request request(0, data_addr, CHECK_SIZE, Flags<unsigned int>(), pc_addr, 0, 0); MemCmd::Command command; if (type == CacheRequestType_IFETCH) { command = MemCmd::ReadReq; request.setFlags(Request::INST_FETCH); } else if (type == CacheRequestType_LD || type == CacheRequestType_IFETCH) { command = MemCmd::ReadReq; } else if (type == CacheRequestType_ST) { command = MemCmd::WriteReq; } else if (type == CacheRequestType_ATOMIC) { command = MemCmd::SwapReq; // TODO -- differentiate between atomic types } else { panic("Cannot convert request to packet"); } Packet pkt(&request, command, 0); // TODO -- make dest a real NodeID Sequencer* sequencer_ptr = initiatingSequencer(); if (sequencer_ptr->isReady(&pkt) == false) { DEBUG_MSG(TESTER_COMP, MedPrio, "failed to initiate check - sequencer not ready\n"); } else { DEBUG_MSG(TESTER_COMP, MedPrio, "initiating check - successful\n"); DEBUG_MSG(TESTER_COMP, MedPrio, m_status); m_status = TesterStatus_Check_Pending; sequencer_ptr->makeRequest(&pkt); } DEBUG_MSG(TESTER_COMP, MedPrio, m_status); } void Check::performCallback(NodeID proc, SubBlock& data) { Address address = data.getAddress(); // assert(getAddress() == address); // This isn't exactly right since we now have multi-byte checks assert(getAddress().getLineAddress() == address.getLineAddress()); DEBUG_MSG(TESTER_COMP, MedPrio, "Callback"); DEBUG_EXPR(TESTER_COMP, MedPrio, *this); if (m_status == TesterStatus_Action_Pending) { DEBUG_MSG(TESTER_COMP, MedPrio, "Action callback"); // Perform store data.setByte(0, m_value+m_store_count); // We store one byte at a time m_store_count++; if (m_store_count == CHECK_SIZE) { m_status = TesterStatus_Ready; } else { m_status = TesterStatus_Idle; } } else if (m_status == TesterStatus_Check_Pending) { DEBUG_MSG(TESTER_COMP, MedPrio, "Check callback"); // Perform load/check for(int byte_number=0; byte_number<CHECK_SIZE; byte_number++) { if (uint8(m_value+byte_number) != data.getByte(byte_number) && (DATA_BLOCK == true)) { WARN_EXPR(proc); WARN_EXPR(address); WARN_EXPR(data); WARN_EXPR(byte_number); WARN_EXPR((int)m_value+byte_number); WARN_EXPR((int)data.getByte(byte_number)); WARN_EXPR(*this); WARN_EXPR(g_eventQueue_ptr->getTime()); ERROR_MSG("Action/check failure"); } } DEBUG_MSG(TESTER_COMP, HighPrio, "Action/check success:"); DEBUG_EXPR(TESTER_COMP, HighPrio, *this); DEBUG_EXPR(TESTER_COMP, MedPrio, data); m_status = TesterStatus_Idle; pickValue(); } else { WARN_EXPR(*this); WARN_EXPR(proc); WARN_EXPR(data); WARN_EXPR(m_status); WARN_EXPR(g_eventQueue_ptr->getTime()); ERROR_MSG("Unexpected TesterStatus"); } DEBUG_EXPR(TESTER_COMP, MedPrio, proc); DEBUG_EXPR(TESTER_COMP, MedPrio, data); DEBUG_EXPR(TESTER_COMP, MedPrio, getAddress().getLineAddress()); DEBUG_MSG(TESTER_COMP, MedPrio, "Callback done"); DEBUG_EXPR(TESTER_COMP, MedPrio, *this); } void Check::changeAddress(const Address& address) { assert((m_status == TesterStatus_Idle) || (m_status == TesterStatus_Ready)); m_status = TesterStatus_Idle; m_address = address; m_store_count = 0; } Sequencer* Check::initiatingSequencer() const { return g_system_ptr->getChip(m_initiatingNode/RubyConfig::numberOfProcsPerChip())->getSequencer(m_initiatingNode%RubyConfig::numberOfProcsPerChip()); } void Check::pickValue() { assert(m_status == TesterStatus_Idle); m_status = TesterStatus_Idle; // DEBUG_MSG(TESTER_COMP, MedPrio, m_status); DEBUG_MSG(TESTER_COMP, MedPrio, *this); m_value = random() & 0xff; // One byte // DEBUG_MSG(TESTER_COMP, MedPrio, m_value); DEBUG_MSG(TESTER_COMP, MedPrio, *this); m_store_count = 0; } void Check::pickInitiatingNode() { assert((m_status == TesterStatus_Idle) || (m_status == TesterStatus_Ready)); m_status = TesterStatus_Idle; DEBUG_MSG(TESTER_COMP, MedPrio, m_status); m_initiatingNode = (random() % RubyConfig::numberOfProcessors()); DEBUG_MSG(TESTER_COMP, MedPrio, m_initiatingNode); m_store_count = 0; } void Check::print(ostream& out) const { out << "[" << m_address << ", value: " << (int) m_value << ", status: " << m_status << ", initiating node: " << m_initiatingNode << ", store_count: " << m_store_count << "]" << flush; } <|endoftext|>
<commit_before>/* * Copyright (c) ICG. All rights reserved. * * Institute for Computer Graphics and Vision * Graz University of Technology / Austria * * * 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. * * * Project : ImageUtilities * Module : Unit Tests * Class : none * Language : C++ * Description : Unit tests for ImageReader class * * Author : Manuel Werlberger * EMail : [email protected] * */ // system includes #include <iostream> #include <cuda_runtime.h> //#include <cv.h> #include <highgui.h> #include <iucore.h> #include <iuio.h> #include <iugui.h> using namespace iu; int main(int argc, char** argv) { if(argc < 2) { std::cout << "You have to provide at least a filename for reading an image." << std::endl; exit(EXIT_FAILURE); } const std::string filename = argv[1]; cv::Mat cvim = cv::imread(filename, 0); cv::imshow("OpenCV Mat image", cvim); /* host images */ iu::ImageCpu_8u_C1* im_8u_C1 = iu::imread_8u_C1(filename); iu::imshow(im_8u_C1, "8u_C1 host image"); iu::imsave(im_8u_C1, "out_8u_C1_host.png"); iu::ImageCpu_8u_C3* im_8u_C3 = iu::imread_8u_C3(filename); iu::imshow(im_8u_C3, "8u_C3 host image"); iu::imsave(im_8u_C3, "out_8u_C3_host.png"); iu::ImageCpu_8u_C4* im_8u_C4 = iu::imread_8u_C4(filename); iu::imshow(im_8u_C4, "8u_C4 host image"); iu::imsave(im_8u_C4, "out_8u_C4_host.png"); iu::ImageCpu_32f_C1* im_32f_C1 = iu::imread_32f_C1(filename); iu::imshow(im_32f_C1, "32f_C1 host image"); iu::imsave(im_32f_C1, "out_32f_C1_host.png"); iu::ImageCpu_32f_C3* im_32f_C3 = iu::imread_32f_C3(filename); iu::imshow(im_32f_C3, "32f_C3 host image"); iu::imsave(im_32f_C3, "out_32f_C3_host.png"); iu::ImageCpu_32f_C4* im_32f_C4 = iu::imread_32f_C4(filename); iu::imshow(im_32f_C4, "32f_C4 host image"); iu::imsave(im_32f_C4, "out_32f_C4_host.png"); /* device images */ iu::ImageNpp_8u_C1* cuim_8u_C1 = iu::imread_cu8u_C1(filename); iu::imshow(cuim_8u_C1, "8u_C1 device image"); iu::imsave(cuim_8u_C1, "out_8u_C1_device.png"); iu::ImageNpp_8u_C4* cuim_8u_C4 = iu::imread_cu8u_C4(filename); iu::imshow(cuim_8u_C4, "8u_C4 device image"); iu::imsave(cuim_8u_C4, "out_8u_C4_device.png"); iu::ImageNpp_32f_C1* cuim_32f_C1 = iu::imread_cu32f_C1(filename); iu::imshow(cuim_32f_C1, "32f_C1 device image"); iu::imsave(cuim_32f_C1, "out_32f_C1_device.png"); iu::ImageNpp_32f_C4* cuim_32f_C4 = iu::imread_cu32f_C4(filename); iu::imshow(cuim_32f_C4, "32f_C4 device image"); iu::imsave(cuim_32f_C4, "out_32f_C4_device.png"); std::cout << std::endl; std::cout << "**************************************************************************" << std::endl; // std::cout << "* Everything seem to be ok. -- All assertions passed. *" << std::endl; std::cout << "* Look at the images and press a key to close the windows and derminate the unittests. *" << std::endl; std::cout << "**************************************************************************" << std::endl; std::cout << std::endl; cv::waitKey(); // CLEANUP delete(im_8u_C1); delete(cuim_8u_C1); delete(im_32f_C1); delete(cuim_32f_C1); return EXIT_SUCCESS; } <commit_msg><commit_after>/* * Copyright (c) ICG. All rights reserved. * * Institute for Computer Graphics and Vision * Graz University of Technology / Austria * * * 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. * * * Project : ImageUtilities * Module : Unit Tests * Class : none * Language : C++ * Description : Unit tests for ImageReader class * * Author : Manuel Werlberger * EMail : [email protected] * */ // system includes #include <iostream> #include <cuda_runtime.h> //#include <cv.h> #include <highgui.h> #include <iucore.h> #include <iuio.h> #include <iugui.h> using namespace iu; int main(int argc, char** argv) { if(argc < 2) { std::cout << "You have to provide at least a filename for reading an image." << std::endl; exit(EXIT_FAILURE); } const std::string filename = argv[1]; cv::Mat cvim = cv::imread(filename, 0); cv::imshow("OpenCV grayscale image", cvim); cv::Mat cvim_rgb = cv::imread(filename, 1); cv::imshow("OpenCV color image", cvim_rgb); cv::imwrite("out_cv_gray.png", cvim); cv::imwrite("out_cv_color.png", cvim_rgb); /* host images */ iu::ImageCpu_8u_C1* im_8u_C1 = iu::imread_8u_C1(filename); iu::imshow(im_8u_C1, "8u_C1 host image"); iu::imsave(im_8u_C1, "out_8u_C1_host.png"); iu::ImageCpu_8u_C3* im_8u_C3 = iu::imread_8u_C3(filename); iu::imshow(im_8u_C3, "8u_C3 host image"); iu::imsave(im_8u_C3, "out_8u_C3_host.png"); iu::ImageCpu_8u_C4* im_8u_C4 = iu::imread_8u_C4(filename); iu::imshow(im_8u_C4, "8u_C4 host image"); iu::imsave(im_8u_C4, "out_8u_C4_host.png"); iu::ImageCpu_32f_C1* im_32f_C1 = iu::imread_32f_C1(filename); iu::imshow(im_32f_C1, "32f_C1 host image"); iu::imsave(im_32f_C1, "out_32f_C1_host.png"); iu::ImageCpu_32f_C3* im_32f_C3 = iu::imread_32f_C3(filename); iu::imshow(im_32f_C3, "32f_C3 host image"); iu::imsave(im_32f_C3, "out_32f_C3_host.png"); iu::ImageCpu_32f_C4* im_32f_C4 = iu::imread_32f_C4(filename); iu::imshow(im_32f_C4, "32f_C4 host image"); iu::imsave(im_32f_C4, "out_32f_C4_host.png"); /* device images */ iu::ImageNpp_8u_C1* cuim_8u_C1 = iu::imread_cu8u_C1(filename); iu::imshow(cuim_8u_C1, "8u_C1 device image"); iu::imsave(cuim_8u_C1, "out_8u_C1_device.png"); iu::ImageNpp_8u_C4* cuim_8u_C4 = iu::imread_cu8u_C4(filename); iu::imshow(cuim_8u_C4, "8u_C4 device image"); iu::imsave(cuim_8u_C4, "out_8u_C4_device.png"); iu::ImageNpp_32f_C1* cuim_32f_C1 = iu::imread_cu32f_C1(filename); iu::imshow(cuim_32f_C1, "32f_C1 device image"); iu::imsave(cuim_32f_C1, "out_32f_C1_device.png"); iu::ImageNpp_32f_C4* cuim_32f_C4 = iu::imread_cu32f_C4(filename); iu::imshow(cuim_32f_C4, "32f_C4 device image"); iu::imsave(cuim_32f_C4, "out_32f_C4_device.png"); std::cout << std::endl; std::cout << "**************************************************************************" << std::endl; // std::cout << "* Everything seem to be ok. -- All assertions passed. *" << std::endl; std::cout << "* Look at the images and press a key to close the windows and derminate the unittests. *" << std::endl; std::cout << "**************************************************************************" << std::endl; std::cout << std::endl; cv::waitKey(); // CLEANUP delete(im_8u_C1); delete(cuim_8u_C1); delete(im_32f_C1); delete(cuim_32f_C1); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #ifndef _Stroika_Foundation_Containers_Concrete_Sequence_Factory_inl_ #define _Stroika_Foundation_Containers_Concrete_Sequence_Factory_inl_ #include "Sequence_stdvector.h" namespace Stroika { namespace Foundation { namespace Containers { namespace Concrete { /* ******************************************************************************** **************************** Sequence_Factory<T> ******************************* ******************************************************************************** */ template <typename T> atomic<Sequence<T> (*) ()> Sequence_Factory<T>::sFactory_ (nullptr); template <typename T> inline Sequence<T> Sequence_Factory<T>::mk () { /* * Would have been more performant to just and assure always properly set, but to initialize * sFactory_ with a value other than nullptr requires waiting until after main() - so causes problems * with containers constructed before main. * * This works more generally (and with hopefully modest enough performance impact). */ auto f = sFactory_.load (); if (f == nullptr) { f = &Default_; } return f (); } template <typename T> void Sequence_Factory<T>::Register (Sequence<T> (*factory) ()) { sFactory_ = factory; } template <typename T> Sequence<T> Sequence_Factory<T>::Default_ () { return Sequence_stdvector<T> (); } } } } } #endif /* _Stroika_Foundation_Containers_Concrete_Sequence_Factory_inl_ */ <commit_msg>Go back to Sequence_Array because Seqeunce_stdvector still buggy in case of nested iterators - regrest 45 fails - must complete this soon!)<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #ifndef _Stroika_Foundation_Containers_Concrete_Sequence_Factory_inl_ #define _Stroika_Foundation_Containers_Concrete_Sequence_Factory_inl_ #include "Sequence_Array.h" namespace Stroika { namespace Foundation { namespace Containers { namespace Concrete { /* ******************************************************************************** **************************** Sequence_Factory<T> ******************************* ******************************************************************************** */ template <typename T> atomic<Sequence<T> (*) ()> Sequence_Factory<T>::sFactory_ (nullptr); template <typename T> inline Sequence<T> Sequence_Factory<T>::mk () { /* * Would have been more performant to just and assure always properly set, but to initialize * sFactory_ with a value other than nullptr requires waiting until after main() - so causes problems * with containers constructed before main. * * This works more generally (and with hopefully modest enough performance impact). */ auto f = sFactory_.load (); if (f == nullptr) { f = &Default_; } return f (); } template <typename T> void Sequence_Factory<T>::Register (Sequence<T> (*factory) ()) { sFactory_ = factory; } template <typename T> Sequence<T> Sequence_Factory<T>::Default_ () { return Sequence_Array<T> (); } } } } } #endif /* _Stroika_Foundation_Containers_Concrete_Sequence_Factory_inl_ */ <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2012. All rights reserved */ #ifndef _Stroika_Foundation_Containers_Concrete_Tally_LinkedList_inl_ #define _Stroika_Foundation_Containers_Concrete_Tally_LinkedList_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "Private/LinkedList.h" #include "../../Memory/BlockAllocated.h" namespace Stroika { namespace Foundation { namespace Containers { namespace Concrete { template <typename T> class Tally_LinkedList<T>::Rep_ : public Tally<T>::_IRep { private: typedef _IRep inherited; public: Rep_ (); Rep_ (const Rep_& from); public: DECLARE_USE_BLOCK_ALLOCATION (Rep_); // Iterable<T>::_IRep overrides public: #if qCompilerAndStdLib_IllUnderstoodTemplateConfusionOverTBug virtual typename Iterable<TallyEntry<T>>::_SharedPtrIRep Clone () const override { return typename Iterable<TallyEntry<T>>::_SharedPtrIRep (new Rep_ (*this)); } #else virtual typename Iterable<TallyEntry<T>>::_SharedPtrIRep Clone () const override; #endif virtual size_t GetLength () const override; virtual bool IsEmpty () const override; virtual Iterator<TallyEntry<T>> MakeIterator () const override; virtual void Apply (typename Rep_::_APPLY_ARGTYPE doToElement) const override; virtual Iterator<TallyEntry<T>> ApplyUntilTrue (typename Rep_::_APPLYUNTIL_ARGTYPE doToElement) const override; // Tally<T>::_IRep overrides public: virtual bool Contains (T item) const override; virtual void Compact () override; virtual void RemoveAll () override; virtual void Add (T item, size_t count) override; virtual void Remove (T item, size_t count) override; virtual size_t TallyOf (T item) const override; virtual shared_ptr<typename Iterator<T>::IRep> MakeBagIterator () const override; virtual typename Tally<T>::TallyMutator MakeTallyMutator () override; private: LinkedList_Patch<TallyEntry<T>> fData; friend class Tally_LinkedList<T>::MutatorRep_; }; template <typename T> class Tally_LinkedList<T>::MutatorRep_ : public Tally<T>::TallyMutator::IRep { public: MutatorRep_ (typename Tally_LinkedList<T>::Rep_& owner); public: DECLARE_USE_BLOCK_ALLOCATION (MutatorRep_); public: virtual bool More (TallyEntry<T>* current, bool advance) override; virtual bool StrongEquals (const typename Iterator<TallyEntry<T> >::IRep* rhs) const override; virtual shared_ptr<typename Iterator<TallyEntry<T> >::IRep> Clone () const override; virtual void RemoveCurrent () override; virtual void UpdateCount (size_t newCount) override; private: LinkedListMutator_Patch<TallyEntry<T>> fIterator; }; /* ******************************************************************************** ********************** Tally_LinkedList<T>::MutatorRep_ ************************ ******************************************************************************** */ template <typename T> Tally_LinkedList<T>::MutatorRep_::MutatorRep_ (Rep_& owner) : fIterator (owner.fData) { } template <typename T> bool Tally_LinkedList<T>::MutatorRep_::More (TallyEntry<T>* current, bool advance) { return (fIterator.More (current, advance)); } template <typename T> bool Tally_LinkedList<T>::MutatorRep_::StrongEquals (const typename Iterator<TallyEntry<T>>::IRep* rhs) const { AssertNotImplemented (); return false; } template <typename T> shared_ptr<typename Iterator<TallyEntry<T>>::IRep> Tally_LinkedList<T>::MutatorRep_::Clone () const { return shared_ptr<typename Iterator<TallyEntry<T>>::IRep> (new MutatorRep_ (*this)); } template <typename T> void Tally_LinkedList<T>::MutatorRep_::RemoveCurrent () { fIterator.RemoveCurrent (); } template <typename T> void Tally_LinkedList<T>::MutatorRep_::UpdateCount (size_t newCount) { if (newCount == 0) { fIterator.RemoveCurrent (); } else { TallyEntry<T> c = fIterator.Current (); c.fCount = newCount; fIterator.UpdateCurrent (c); } } /* ******************************************************************************** ************************* Tally_LinkedList<T>::Rep_ **************************** ******************************************************************************** */ template <typename T> inline Tally_LinkedList<T>::Rep_::Rep_ () : fData () { } template <typename T> inline Tally_LinkedList<T>::Rep_::Rep_ (const Rep_& from) : fData (from.fData) { } template <typename T> size_t Tally_LinkedList<T>::Rep_::GetLength () const { return (fData.GetLength ()); } template <typename T> bool Tally_LinkedList<T>::Rep_::IsEmpty () const { return (fData.GetLength () == 0); } template <typename T> Iterator<TallyEntry<T>> Tally_LinkedList<T>::Rep_::MakeIterator () const { // const cast cuz this mutator won't really be used to change anything - except stuff like // link list of owned iterators Iterator<TallyEntry<T>> tmp = Iterator<TallyEntry<T>> (typename Iterator<TallyEntry<T>>::SharedByValueRepType (shared_ptr<typename Iterator<TallyEntry<T>>::IRep> (new MutatorRep_ (*const_cast<Rep_*> (this))))); tmp++; //tmphack - redo iterator impl itself return tmp; } template <typename T> void Tally_LinkedList<T>::Rep_::Apply (typename Rep_::_APPLY_ARGTYPE doToElement) const { return _Apply (doToElement); } template <typename T> Iterator<TallyEntry<T>> Tally_LinkedList<T>::Rep_::ApplyUntilTrue (typename Rep_::_APPLYUNTIL_ARGTYPE doToElement) const { return _ApplyUntilTrue (doToElement); } template <typename T> bool Tally_LinkedList<T>::Rep_::Contains (T item) const { TallyEntry<T> c; for (LinkedListIterator<TallyEntry<T>> it (fData); it.More (&c, true); ) { if (c.fItem == item) { Assert (c.fCount != 0); return (true); } } return (false); } template <typename T> void Tally_LinkedList<T>::Rep_::Compact () { } #if !qCompilerAndStdLib_IllUnderstoodTemplateConfusionOverTBug template <typename T> typename Iterable<TallyEntry<T>>::_SharedPtrIRep Tally_LinkedList<T>::Rep_::Clone () const { return typename Iterable<TallyEntry<T>>::_SharedPtrIRep (new Rep_ (*this)); } #endif template <typename T> void Tally_LinkedList<T>::Rep_::Add (T item, size_t count) { if (count != 0) { TallyEntry<T> current (item); for (LinkedListMutator_Patch<TallyEntry<T> > it (fData); it.More (&current, true); ) { if (current.fItem == item) { current.fCount += count; it.UpdateCurrent (current); return; } } fData.Prepend (TallyEntry<T> (item, count)); } } template <typename T> void Tally_LinkedList<T>::Rep_::Remove (T item, size_t count) { if (count != 0) { TallyEntry<T> current (item); for (LinkedListMutator_Patch<TallyEntry<T> > it (fData); it.More (&current, true); ) { if (current.fItem == item) { if (current.fCount > count) { current.fCount -= count; } else { current.fCount = 0; // Should this be an underflow excpetion, assertion??? } if (current.fCount == 0) { it.RemoveCurrent (); } else { it.UpdateCurrent (current); } break; } } } } template <typename T> void Tally_LinkedList<T>::Rep_::RemoveAll () { fData.RemoveAll (); } template <typename T> size_t Tally_LinkedList<T>::Rep_::TallyOf (T item) const { TallyEntry<T> c; for (LinkedListIterator<TallyEntry<T> > it (fData); it.More (&c, true); ) { if (c.fItem == item) { Ensure (c.fCount != 0); return (c.fCount); } } return (0); } template <typename T> shared_ptr<typename Iterator<T>::IRep> Tally_LinkedList<T>::Rep_::MakeBagIterator () const { return shared_ptr<typename Iterator<T>::IRep> (new _TallyEntryToItemIterator (MakeIterator ())); } template <typename T> typename Tally<T>::TallyMutator Tally_LinkedList<T>::Rep_::MakeTallyMutator () { return TallyMutator (new MutatorRep_ (*this)); } /* ******************************************************************************** **************************** Tally_LinkedList<T> ******************************* ******************************************************************************** */ template <typename T> Tally_LinkedList<T>::Tally_LinkedList () : inherited (new Rep_ ()) { } template <typename T> Tally_LinkedList<T>::Tally_LinkedList (const T* items, size_t size) : Tally<T> (new Rep_ ()) { AddItems (items, size); } template <typename T> Tally_LinkedList<T>::Tally_LinkedList (const Tally<T>& src) : Tally<T> (new Rep_ ()) { operator+= (src); } template <typename T> inline Tally_LinkedList<T>::Tally_LinkedList (const Tally_LinkedList<T>& src) : Tally<T> (src) { } template <typename T> inline Tally_LinkedList<T>& Tally_LinkedList<T>::operator= (const Tally_LinkedList<T>& src) { Tally<T>::operator= (src); return (*this); } } } } } #endif /* _Stroika_Foundation_Containers_Concrete_Tally_LinkedList_inl_ */ <commit_msg>gcc compat on Tally templates<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2012. All rights reserved */ #ifndef _Stroika_Foundation_Containers_Concrete_Tally_LinkedList_inl_ #define _Stroika_Foundation_Containers_Concrete_Tally_LinkedList_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "Private/LinkedList.h" #include "../../Memory/BlockAllocated.h" namespace Stroika { namespace Foundation { namespace Containers { namespace Concrete { template <typename T> class Tally_LinkedList<T>::Rep_ : public Tally<T>::_IRep { private: typedef typename Tally<T>::_IRep inherited; public: Rep_ (); Rep_ (const Rep_& from); public: DECLARE_USE_BLOCK_ALLOCATION (Rep_); // Iterable<T>::_IRep overrides public: #if qCompilerAndStdLib_IllUnderstoodTemplateConfusionOverTBug virtual typename Iterable<TallyEntry<T>>::_SharedPtrIRep Clone () const override { return typename Iterable<TallyEntry<T>>::_SharedPtrIRep (new Rep_ (*this)); } #else virtual typename Iterable<TallyEntry<T>>::_SharedPtrIRep Clone () const override; #endif virtual size_t GetLength () const override; virtual bool IsEmpty () const override; virtual Iterator<TallyEntry<T>> MakeIterator () const override; virtual void Apply (typename Rep_::_APPLY_ARGTYPE doToElement) const override; virtual Iterator<TallyEntry<T>> ApplyUntilTrue (typename Rep_::_APPLYUNTIL_ARGTYPE doToElement) const override; // Tally<T>::_IRep overrides public: virtual bool Contains (T item) const override; virtual void Compact () override; virtual void RemoveAll () override; virtual void Add (T item, size_t count) override; virtual void Remove (T item, size_t count) override; virtual size_t TallyOf (T item) const override; virtual shared_ptr<typename Iterator<T>::IRep> MakeBagIterator () const override; virtual typename Tally<T>::TallyMutator MakeTallyMutator () override; private: LinkedList_Patch<TallyEntry<T>> fData; friend class Tally_LinkedList<T>::MutatorRep_; }; template <typename T> class Tally_LinkedList<T>::MutatorRep_ : public Tally<T>::TallyMutator::IRep { public: MutatorRep_ (typename Tally_LinkedList<T>::Rep_& owner); public: DECLARE_USE_BLOCK_ALLOCATION (MutatorRep_); public: virtual bool More (TallyEntry<T>* current, bool advance) override; virtual bool StrongEquals (const typename Iterator<TallyEntry<T> >::IRep* rhs) const override; virtual shared_ptr<typename Iterator<TallyEntry<T> >::IRep> Clone () const override; virtual void RemoveCurrent () override; virtual void UpdateCount (size_t newCount) override; private: LinkedListMutator_Patch<TallyEntry<T>> fIterator; }; /* ******************************************************************************** ********************** Tally_LinkedList<T>::MutatorRep_ ************************ ******************************************************************************** */ template <typename T> Tally_LinkedList<T>::MutatorRep_::MutatorRep_ (Rep_& owner) : fIterator (owner.fData) { } template <typename T> bool Tally_LinkedList<T>::MutatorRep_::More (TallyEntry<T>* current, bool advance) { return (fIterator.More (current, advance)); } template <typename T> bool Tally_LinkedList<T>::MutatorRep_::StrongEquals (const typename Iterator<TallyEntry<T>>::IRep* rhs) const { AssertNotImplemented (); return false; } template <typename T> shared_ptr<typename Iterator<TallyEntry<T>>::IRep> Tally_LinkedList<T>::MutatorRep_::Clone () const { return shared_ptr<typename Iterator<TallyEntry<T>>::IRep> (new MutatorRep_ (*this)); } template <typename T> void Tally_LinkedList<T>::MutatorRep_::RemoveCurrent () { fIterator.RemoveCurrent (); } template <typename T> void Tally_LinkedList<T>::MutatorRep_::UpdateCount (size_t newCount) { if (newCount == 0) { fIterator.RemoveCurrent (); } else { TallyEntry<T> c = fIterator.Current (); c.fCount = newCount; fIterator.UpdateCurrent (c); } } /* ******************************************************************************** ************************* Tally_LinkedList<T>::Rep_ **************************** ******************************************************************************** */ template <typename T> inline Tally_LinkedList<T>::Rep_::Rep_ () : fData () { } template <typename T> inline Tally_LinkedList<T>::Rep_::Rep_ (const Rep_& from) : fData (from.fData) { } template <typename T> size_t Tally_LinkedList<T>::Rep_::GetLength () const { return (fData.GetLength ()); } template <typename T> bool Tally_LinkedList<T>::Rep_::IsEmpty () const { return (fData.GetLength () == 0); } template <typename T> Iterator<TallyEntry<T>> Tally_LinkedList<T>::Rep_::MakeIterator () const { // const cast cuz this mutator won't really be used to change anything - except stuff like // link list of owned iterators Iterator<TallyEntry<T>> tmp = Iterator<TallyEntry<T>> (typename Iterator<TallyEntry<T>>::SharedByValueRepType (shared_ptr<typename Iterator<TallyEntry<T>>::IRep> (new MutatorRep_ (*const_cast<Rep_*> (this))))); tmp++; //tmphack - redo iterator impl itself return tmp; } template <typename T> void Tally_LinkedList<T>::Rep_::Apply (typename Rep_::_APPLY_ARGTYPE doToElement) const { return _Apply (doToElement); } template <typename T> Iterator<TallyEntry<T>> Tally_LinkedList<T>::Rep_::ApplyUntilTrue (typename Rep_::_APPLYUNTIL_ARGTYPE doToElement) const { return _ApplyUntilTrue (doToElement); } template <typename T> bool Tally_LinkedList<T>::Rep_::Contains (T item) const { TallyEntry<T> c; for (LinkedListIterator<TallyEntry<T>> it (fData); it.More (&c, true); ) { if (c.fItem == item) { Assert (c.fCount != 0); return (true); } } return (false); } template <typename T> void Tally_LinkedList<T>::Rep_::Compact () { } #if !qCompilerAndStdLib_IllUnderstoodTemplateConfusionOverTBug template <typename T> typename Iterable<TallyEntry<T>>::_SharedPtrIRep Tally_LinkedList<T>::Rep_::Clone () const { return typename Iterable<TallyEntry<T>>::_SharedPtrIRep (new Rep_ (*this)); } #endif template <typename T> void Tally_LinkedList<T>::Rep_::Add (T item, size_t count) { if (count != 0) { TallyEntry<T> current (item); for (LinkedListMutator_Patch<TallyEntry<T> > it (fData); it.More (&current, true); ) { if (current.fItem == item) { current.fCount += count; it.UpdateCurrent (current); return; } } fData.Prepend (TallyEntry<T> (item, count)); } } template <typename T> void Tally_LinkedList<T>::Rep_::Remove (T item, size_t count) { if (count != 0) { TallyEntry<T> current (item); for (LinkedListMutator_Patch<TallyEntry<T> > it (fData); it.More (&current, true); ) { if (current.fItem == item) { if (current.fCount > count) { current.fCount -= count; } else { current.fCount = 0; // Should this be an underflow excpetion, assertion??? } if (current.fCount == 0) { it.RemoveCurrent (); } else { it.UpdateCurrent (current); } break; } } } } template <typename T> void Tally_LinkedList<T>::Rep_::RemoveAll () { fData.RemoveAll (); } template <typename T> size_t Tally_LinkedList<T>::Rep_::TallyOf (T item) const { TallyEntry<T> c; for (LinkedListIterator<TallyEntry<T> > it (fData); it.More (&c, true); ) { if (c.fItem == item) { Ensure (c.fCount != 0); return (c.fCount); } } return (0); } template <typename T> shared_ptr<typename Iterator<T>::IRep> Tally_LinkedList<T>::Rep_::MakeBagIterator () const { return shared_ptr<typename Iterator<T>::IRep> (new _TallyEntryToItemIterator (MakeIterator ())); } template <typename T> typename Tally<T>::TallyMutator Tally_LinkedList<T>::Rep_::MakeTallyMutator () { return TallyMutator (new MutatorRep_ (*this)); } /* ******************************************************************************** **************************** Tally_LinkedList<T> ******************************* ******************************************************************************** */ template <typename T> Tally_LinkedList<T>::Tally_LinkedList () : inherited (new Rep_ ()) { } template <typename T> Tally_LinkedList<T>::Tally_LinkedList (const T* items, size_t size) : Tally<T> (new Rep_ ()) { AddItems (items, size); } template <typename T> Tally_LinkedList<T>::Tally_LinkedList (const Tally<T>& src) : Tally<T> (new Rep_ ()) { operator+= (src); } template <typename T> inline Tally_LinkedList<T>::Tally_LinkedList (const Tally_LinkedList<T>& src) : Tally<T> (src) { } template <typename T> inline Tally_LinkedList<T>& Tally_LinkedList<T>::operator= (const Tally_LinkedList<T>& src) { Tally<T>::operator= (src); return (*this); } } } } } #endif /* _Stroika_Foundation_Containers_Concrete_Tally_LinkedList_inl_ */ <|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 <mitkTestingMacros.h> #include <mitkTestFixture.h> #include "mitkIOUtil.h" #include <cmath> #include <mitkGIFVolumetricStatistics.h> class mitkGIFVolumetricStatisticsTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkGIFVolumetricStatisticsTestSuite); MITK_TEST(ImageDescription_PhantomTest); CPPUNIT_TEST_SUITE_END(); private: mitk::Image::Pointer m_IBSI_Phantom_Image_Small; mitk::Image::Pointer m_IBSI_Phantom_Image_Large; mitk::Image::Pointer m_IBSI_Phantom_Mask_Small; mitk::Image::Pointer m_IBSI_Phantom_Mask_Large; public: void setUp(void) override { m_IBSI_Phantom_Image_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Small.nrrd")); m_IBSI_Phantom_Image_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Large.nrrd")); m_IBSI_Phantom_Mask_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Small.nrrd")); m_IBSI_Phantom_Mask_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Large.nrrd")); } void ImageDescription_PhantomTest() { mitk::GIFVolumetricStatistics::Pointer featureCalculator = mitk::GIFVolumetricStatistics::New(); featureCalculator->SetUseBinsize(true); featureCalculator->SetBinsize(1.0); featureCalculator->SetUseMinimumIntensity(true); featureCalculator->SetUseMaximumIntensity(true); featureCalculator->SetMinimumIntensity(0.5); featureCalculator->SetMaximumIntensity(6.5); auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large); std::map<std::string, double> results; for (auto valuePair : featureList) { MITK_INFO << valuePair.first << " : " << valuePair.second; results[valuePair.first] = valuePair.second; } CPPUNIT_ASSERT_EQUAL_MESSAGE("Volume Statistic should calculate 33 features.", std::size_t(33), featureList.size()); // These values are obtained in cooperation with IBSI // Default accuracy is 0.01 CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Volume (mesh based) with Large IBSI Phantom Image", 556, results["Volumetric Features::Volume (mesh based)"], 1.0); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Volume (voxel based) with Large IBSI Phantom Image", 592, results["Volumetric Features::Volume (voxel based)"], 1.0); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Surface (mesh based) with Large IBSI Phantom Image", 388, results["Volumetric Features::Surface (mesh based)"], 1.0); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Surface to volume ratio (mesh based) with Large IBSI Phantom Image", 0.698, results["Volumetric Features::Surface to volume ratio (mesh based)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Compactness 1 (mesh based) with Large IBSI Phantom Image", 0.0437, results["Volumetric Features::Compactness 1 (mesh based)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Compactness 2 (mesh based) with Large IBSI Phantom Image", 0.678, results["Volumetric Features::Compactness 2 (mesh based)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Spherical disproportion (mesh based) with Large IBSI Phantom Image", 1.14, results["Volumetric Features::Spherical disproportion (mesh based)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Sphericity (mesh based) with Large IBSI Phantom Image", 0.879, results["Volumetric Features::Sphericity (mesh based)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Asphericity (mesh based) with Large IBSI Phantom Image", 0.138, results["Volumetric Features::Asphericity (mesh based)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Ceentre of mass shift with Large IBSI Phantom Image", 0.672, results["Volumetric Features::Centre of mass shift"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Maximum 3D Diameter with Large IBSI Phantom Image", 11.66, results["Volumetric Features::Maximum 3D Diameter"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::PCA Major axis length with Large IBSI Phantom Image", 11.40, results["Volumetric Features::PCA Major axis length"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::PCA Minor axis length with Large IBSI Phantom Image", 9.31, results["Volumetric Features::PCA Minor axis length"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::PCA Least axis length with Large IBSI Phantom Image", 8.54, results["Volumetric Features::PCA Least axis length"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Elongation with Large IBSI Phantom Image", 0.816, results["Volumetric Features::Elongation"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Flatness with Large IBSI Phantom Image", 0.749, results["Volumetric Features::Flatness"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features:: with Large IBSI Phantom Image", 1.51, results["Volumetric Features::"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features:: with Large IBSI Phantom Image", 1.51, results["Volumetric Features::"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features:: with Large IBSI Phantom Image", 1.51, results["Volumetric Features::"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features:: with Large IBSI Phantom Image", 1.51, results["Volumetric Features::"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features:: with Large IBSI Phantom Image", 1.51, results["Volumetric Features::"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features:: with Large IBSI Phantom Image", 1.51, results["Volumetric Features::"], 0.01); } }; MITK_TEST_SUITE_REGISTRATION(mitkGIFVolumetricStatistics )<commit_msg>Added most features except PCA based<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 <mitkTestingMacros.h> #include <mitkTestFixture.h> #include "mitkIOUtil.h" #include <cmath> #include <mitkGIFVolumetricStatistics.h> class mitkGIFVolumetricStatisticsTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkGIFVolumetricStatisticsTestSuite); MITK_TEST(ImageDescription_PhantomTest); CPPUNIT_TEST_SUITE_END(); private: mitk::Image::Pointer m_IBSI_Phantom_Image_Small; mitk::Image::Pointer m_IBSI_Phantom_Image_Large; mitk::Image::Pointer m_IBSI_Phantom_Mask_Small; mitk::Image::Pointer m_IBSI_Phantom_Mask_Large; public: void setUp(void) override { m_IBSI_Phantom_Image_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Small.nrrd")); m_IBSI_Phantom_Image_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Large.nrrd")); m_IBSI_Phantom_Mask_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Small.nrrd")); m_IBSI_Phantom_Mask_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Large.nrrd")); } void ImageDescription_PhantomTest() { mitk::GIFVolumetricStatistics::Pointer featureCalculator = mitk::GIFVolumetricStatistics::New(); auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large); std::map<std::string, double> results; for (auto valuePair : featureList) { MITK_INFO << valuePair.first << " : " << valuePair.second; results[valuePair.first] = valuePair.second; } CPPUNIT_ASSERT_EQUAL_MESSAGE("Volume Statistic should calculate 33 features.", std::size_t(33), featureList.size()); // These values are obtained in cooperation with IBSI // Default accuracy is 0.01 CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Volume (mesh based) with Large IBSI Phantom Image", 556, results["Volumetric Features::Volume (mesh based)"], 1.0); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Volume (voxel based) with Large IBSI Phantom Image", 592, results["Volumetric Features::Volume (voxel based)"], 1.0); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Surface (mesh based) with Large IBSI Phantom Image", 388, results["Volumetric Features::Surface (mesh based)"], 1.0); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Surface to volume ratio (mesh based) with Large IBSI Phantom Image", 0.698, results["Volumetric Features::Surface to volume ratio (mesh based)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Compactness 1 (mesh based) with Large IBSI Phantom Image", 0.0437, results["Volumetric Features::Compactness 1 (mesh based)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Compactness 2 (mesh based) with Large IBSI Phantom Image", 0.678, results["Volumetric Features::Compactness 2 (mesh based)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Spherical disproportion (mesh based) with Large IBSI Phantom Image", 1.14, results["Volumetric Features::Spherical disproportion (mesh based)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Sphericity (mesh based) with Large IBSI Phantom Image", 0.879, results["Volumetric Features::Sphericity (mesh based)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Asphericity (mesh based) with Large IBSI Phantom Image", 0.138, results["Volumetric Features::Asphericity (mesh based)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Ceentre of mass shift with Large IBSI Phantom Image", 0.672, results["Volumetric Features::Centre of mass shift"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Maximum 3D diameter with Large IBSI Phantom Image", 11.66, results["Volumetric Features::Maximum 3D diameter"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::PCA Major axis length with Large IBSI Phantom Image", 11.40, results["Volumetric Features::PCA Major axis length"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::PCA Minor axis length with Large IBSI Phantom Image", 9.31, results["Volumetric Features::PCA Minor axis length"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::PCA Least axis length with Large IBSI Phantom Image", 8.54, results["Volumetric Features::PCA Least axis length"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::PCA Elongation with Large IBSI Phantom Image", 0.816, results["Volumetric Features::PCA Elongation"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::PCA Flatness with Large IBSI Phantom Image", 0.749, results["Volumetric Features::PCA Flatness"], 0.01); // These values are obtained by running the filter // They might be wrong! CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Voxel Volume with Large IBSI Phantom Image", 8, results["Volumetric Features::Voxel Volume"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Volume (voxel based) with Large IBSI Phantom Image", 592, results["Volumetric Features::Volume (voxel based)"], 0.1); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Surface (voxel based) with Large IBSI Phantom Image", 488, results["Volumetric Features::Surface (voxel based)"], 1.0); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Centre of mass shift (uncorrected) with Large IBSI Phantom Image", 0.672, results["Volumetric Features::Centre of mass shift (uncorrected)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Bounding Box Volume with Large IBSI Phantom Image", 288, results["Volumetric Features::Bounding Box Volume"], 1.0); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Surface to volume ratio (voxel based) with Large IBSI Phantom Image", 0.824, results["Volumetric Features::Surface to volume ratio (voxel based)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Sphericity (voxel based) with Large IBSI Phantom Image", 0.699, results["Volumetric Features::Sphericity (voxel based)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Asphericity (voxel based) with Large IBSI Phantom Image", 0.431, results["Volumetric Features::Asphericity (voxel based)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Compactness 1 (voxel based) with Large IBSI Phantom Image", 0.031, results["Volumetric Features::Compactness 1 (voxel based)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Compactness 1 old (voxel based) with Large IBSI Phantom Image", 5.388, results["Volumetric Features::Compactness 1 old (voxel based)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Compactness 2 (voxel based) with Large IBSI Phantom Image", 0.341, results["Volumetric Features::Compactness 2 (voxel based)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features::Spherical disproportion (voxel based) with Large IBSI Phantom Image", 1.43, results["Volumetric Features::Spherical disproportion (voxel based)"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features:: with Large IBSI Phantom Image", 1.51, results["Volumetric Features::"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features:: with Large IBSI Phantom Image", 1.51, results["Volumetric Features::"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features:: with Large IBSI Phantom Image", 1.51, results["Volumetric Features::"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features:: with Large IBSI Phantom Image", 1.51, results["Volumetric Features::"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features:: with Large IBSI Phantom Image", 1.51, results["Volumetric Features::"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Volumetric Features:: with Large IBSI Phantom Image", 1.51, results["Volumetric Features::"], 0.01); } }; MITK_TEST_SUITE_REGISTRATION(mitkGIFVolumetricStatistics )<|endoftext|>
<commit_before>/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * Copyright (C) 2020 CS Systemes d'Information (CS SI) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "otbExtendedFilenameToWriterOptions.h" #include <iostream> #include <fstream> typedef otb::ExtendedFilenameToWriterOptions FilenameHelperType; int otbExtendedFilenameToWriterOptions(int itkNotUsed(argc), char* argv[]) { // Verify the number of parameters in the command line const char* inputExtendedFilename = argv[1]; const char* outputFilename = argv[2]; FilenameHelperType::Pointer helper = FilenameHelperType::New(); helper->SetExtendedFileName(inputExtendedFilename); std::ofstream file; file.open(outputFilename); file << helper->SimpleFileNameIsSet() << std::endl; file << helper->GetSimpleFileName() << std::endl; file << helper->WriteGEOMFileIsSet() << std::endl; file << helper->GetWriteGEOMFile() << std::endl; file << helper->gdalCreationOptionsIsSet() << std::endl; if (helper->gdalCreationOptionsIsSet()) for (unsigned int i = 0; i < helper->GetgdalCreationOptions().size(); i++) { file << helper->GetgdalCreationOptions()[i] << std::endl; } file << helper->NoDataValueIsSet() << std::endl; if (helper->NoDataValueIsSet()) for (unsigned int i = 0; i < helper->GetNoDataList().size(); i++) { file << helper->GetNoDataList()[i].first << " ; " << helper->GetNoDataList()[i].second << std::endl; } file << helper->SrsValueIsSet() << std::endl; if (helper->SrsValueIsSet()) file << helper->GetSrsValue() << std::endl; return EXIT_SUCCESS; } <commit_msg>PERF: follow OTB guidlines + optimize a loop<commit_after>/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * Copyright (C) 2020 CS Systemes d'Information (CS SI) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "otbExtendedFilenameToWriterOptions.h" #include <iostream> #include <fstream> typedef otb::ExtendedFilenameToWriterOptions FilenameHelperType; int otbExtendedFilenameToWriterOptions(int itkNotUsed(argc), char* argv[]) { // Verify the number of parameters in the command line const char* inputExtendedFilename = argv[1]; const char* outputFilename = argv[2]; FilenameHelperType::Pointer helper = FilenameHelperType::New(); helper->SetExtendedFileName(inputExtendedFilename); std::ofstream file; file.open(outputFilename); file << helper->SimpleFileNameIsSet() << std::endl; file << helper->GetSimpleFileName() << std::endl; file << helper->WriteGEOMFileIsSet() << std::endl; file << helper->GetWriteGEOMFile() << std::endl; file << helper->gdalCreationOptionsIsSet() << std::endl; if (helper->gdalCreationOptionsIsSet()) { for (unsigned int i = 0; i < helper->GetgdalCreationOptions().size(); i++) { file << helper->GetgdalCreationOptions()[i] << std::endl; } } file << helper->NoDataValueIsSet() << std::endl; if (helper->NoDataValueIsSet()) { for (auto const& nodata_kv : helper->GetNoDataList()) { file << nodata_kv.first << " ; " << nodata_kv.second << "\n"; } } file << helper->SrsValueIsSet() << std::endl; if (helper->SrsValueIsSet()) file << helper->GetSrsValue() << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/session/onnxruntime_cxx_api.h" #include "providers.h" #include <memory> #include <vector> #include <iostream> #include <atomic> #include <gtest/gtest.h> #include "test_allocator.h" #include "test_fixture.h" using namespace onnxruntime; void RunSession(OrtAllocator* env, OrtSession* session_object, const std::vector<size_t>& dims_x, const std::vector<float>& values_x, const std::vector<int64_t>& dims_y, const std::vector<float>& values_y) { std::unique_ptr<OrtValue, decltype(&OrtReleaseValue)> value_x(nullptr, OrtReleaseValue); std::vector<OrtValue*> inputs(1); inputs[0] = OrtCreateTensorAsOrtValue(env, dims_x, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT); value_x.reset(inputs[0]); void* raw_data; ORT_THROW_ON_ERROR(OrtGetTensorMutableData(inputs[0], &raw_data)); memcpy(raw_data, values_x.data(), values_x.size() * sizeof(values_x[0])); std::vector<const char*> input_names{"X"}; OrtValue* output_tensor = nullptr; const char* output_names[] = {"Y"}; ORT_THROW_ON_ERROR(OrtRun(session_object, NULL, input_names.data(), inputs.data(), inputs.size(), output_names, 1, &output_tensor)); ASSERT_NE(output_tensor, nullptr); std::unique_ptr<OrtTensorTypeAndShapeInfo> shape_info; { OrtTensorTypeAndShapeInfo* shape_info_ptr; ORT_THROW_ON_ERROR(OrtGetTensorShapeAndType(output_tensor, &shape_info_ptr)); shape_info.reset(shape_info_ptr); } size_t rtensor_dims = OrtGetNumOfDimensions(shape_info.get()); std::vector<int64_t> shape_array(rtensor_dims); OrtGetDimensions(shape_info.get(), shape_array.data(), shape_array.size()); ASSERT_EQ(shape_array, dims_y); size_t total_len = 1; for (size_t i = 0; i != rtensor_dims; ++i) { total_len *= shape_array[i]; } ASSERT_EQ(values_y.size(), total_len); float* f; ORT_THROW_ON_ERROR(OrtGetTensorMutableData(output_tensor, (void**)&f)); for (size_t i = 0; i != total_len; ++i) { ASSERT_EQ(values_y[i], f[i]); } OrtReleaseValue(output_tensor); } template <typename T> void TestInference(OrtEnv* env, T model_uri, const std::vector<size_t>& dims_x, const std::vector<float>& values_x, const std::vector<int64_t>& expected_dims_y, const std::vector<float>& expected_values_y, int provider_type, bool custom_op) { SessionOptionsWrapper sf(env); if (provider_type == 1) { #ifdef USE_CUDA ORT_THROW_ON_ERROR(OrtSessionOptionsAppendExecutionProvider_CUDA(sf, 0)); std::cout << "Running simple inference with cuda provider" << std::endl; #else return; #endif } else if (provider_type == 2) { #ifdef USE_MKLDNN ORT_THROW_ON_ERROR(OrtSessionOptionsAppendExecutionProvider_Mkldnn(sf, 1)); std::cout << "Running simple inference with mkldnn provider" << std::endl; #else return; #endif } else if (provider_type == 3) { #ifdef USE_NUPHAR ORT_THROW_ON_ERROR(OrtSessionOptionsAppendExecutionProvider_Nuphar(sf, 0, "")); std::cout << "Running simple inference with nuphar provider" << std::endl; #else return; #endif } else { std::cout << "Running simple inference with default provider" << std::endl; } if (custom_op) { sf.AppendCustomOpLibPath("libonnxruntime_custom_op_shared_lib_test.so"); } std::unique_ptr<OrtSession, decltype(&OrtReleaseSession)> inference_session(sf.OrtCreateSession(model_uri), OrtReleaseSession); std::unique_ptr<MockedOrtAllocator> default_allocator(std::make_unique<MockedOrtAllocator>()); // Now run RunSession(default_allocator.get(), inference_session.get(), dims_x, values_x, expected_dims_y, expected_values_y); } static constexpr PATH_TYPE MODEL_URI = TSTR("testdata/mul_1.pb"); static constexpr PATH_TYPE CUSTOM_OP_MODEL_URI = TSTR("testdata/foo_1.pb"); class CApiTestWithProvider : public CApiTest, public ::testing::WithParamInterface<int> { }; // Tests that the Foo::Bar() method does Abc. TEST_P(CApiTestWithProvider, simple) { // simple inference test // prepare inputs std::vector<size_t> dims_x = {3, 2}; std::vector<float> values_x = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f}; // prepare expected inputs and outputs std::vector<int64_t> expected_dims_y = {3, 2}; std::vector<float> expected_values_y = {1.0f, 4.0f, 9.0f, 16.0f, 25.0f, 36.0f}; TestInference<PATH_TYPE>(env, MODEL_URI, dims_x, values_x, expected_dims_y, expected_values_y, GetParam(), false); } INSTANTIATE_TEST_CASE_P(CApiTestWithProviders, CApiTestWithProvider, ::testing::Values(0, 1, 2, 3, 4)); #ifndef _WIN32 //doesn't work, failed in type comparison TEST_F(CApiTest, DISABLED_custom_op) { std::cout << "Running custom op inference" << std::endl; std::vector<size_t> dims_x = {3, 2}; std::vector<float> values_x = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f}; // prepare expected inputs and outputs std::vector<int64_t> expected_dims_y = {3, 2}; std::vector<float> expected_values_y = {2.0f, 4.0f, 6.0f, 8.0f, 10.0f, 12.0f}; TestInference<PATH_TYPE>(env, CUSTOM_OP_MODEL_URI, dims_x, values_x, expected_dims_y, expected_values_y, false, true); } #endif #ifdef ORT_RUN_EXTERNAL_ONNX_TESTS TEST_F(CApiTest, create_session_without_session_option) { constexpr PATH_TYPE model_uri = TSTR("../models/opset8/test_squeezenet/model.onnx"); OrtSession* ret; ORT_THROW_ON_ERROR(::OrtCreateSession(env, model_uri, nullptr, &ret)); ASSERT_NE(nullptr, ret); OrtReleaseSession(ret); } #endif TEST_F(CApiTest, create_tensor) { const char* s[] = {"abc", "kmp"}; size_t expected_len = 2; std::unique_ptr<MockedOrtAllocator> default_allocator(std::make_unique<MockedOrtAllocator>()); { std::unique_ptr<OrtValue, decltype(&OrtReleaseValue)> tensor( OrtCreateTensorAsOrtValue(default_allocator.get(), {expected_len}, ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING), OrtReleaseValue); ORT_THROW_ON_ERROR(OrtFillStringTensor(tensor.get(), s, expected_len)); std::unique_ptr<OrtTensorTypeAndShapeInfo> shape_info; { OrtTensorTypeAndShapeInfo* shape_info_ptr; ORT_THROW_ON_ERROR(OrtGetTensorShapeAndType(tensor.get(), &shape_info_ptr)); shape_info.reset(shape_info_ptr); } size_t len = static_cast<size_t>(OrtGetTensorShapeElementCount(shape_info.get())); ASSERT_EQ(len, expected_len); std::vector<int64_t> shape_array(len); size_t data_len; ORT_THROW_ON_ERROR(OrtGetStringTensorDataLength(tensor.get(), &data_len)); std::string result(data_len, '\0'); std::vector<size_t> offsets(len); ORT_THROW_ON_ERROR(OrtGetStringTensorContent(tensor.get(), (void*)result.data(), data_len, offsets.data(), offsets.size())); } } TEST_F(CApiTest, create_tensor_with_data) { float values[] = {3.0f, 1.0f, 2.f, 0.f}; constexpr size_t values_length = sizeof(values) / sizeof(values[0]); OrtAllocatorInfo* info; ORT_THROW_ON_ERROR(OrtCreateAllocatorInfo("Cpu", OrtDeviceAllocator, 0, OrtMemTypeDefault, &info)); std::vector<size_t> dims = {4}; std::unique_ptr<OrtValue, decltype(&OrtReleaseValue)> tensor( OrtCreateTensorWithDataAsOrtValue(info, values, values_length * sizeof(float), dims, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT), OrtReleaseValue); OrtReleaseAllocatorInfo(info); void* new_pointer; ORT_THROW_ON_ERROR(OrtGetTensorMutableData(tensor.get(), &new_pointer)); ASSERT_EQ(new_pointer, values); struct OrtTypeInfo* type_info; ORT_THROW_ON_ERROR(OrtGetTypeInfo(tensor.get(), &type_info)); const struct OrtTensorTypeAndShapeInfo* tensor_info = OrtCastTypeInfoToTensorInfo(type_info); ASSERT_NE(tensor_info, nullptr); ASSERT_EQ(1, OrtGetNumOfDimensions(tensor_info)); OrtReleaseTypeInfo(type_info); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Add test case for pre-allocated output<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/session/onnxruntime_cxx_api.h" #include "providers.h" #include <memory> #include <vector> #include <iostream> #include <atomic> #include <gtest/gtest.h> #include "test_allocator.h" #include "test_fixture.h" using namespace onnxruntime; void RunSession(OrtAllocator* env, OrtSession* session_object, const std::vector<size_t>& dims_x, const std::vector<float>& values_x, const std::vector<int64_t>& dims_y, const std::vector<float>& values_y, OrtValue* output_tensor) { std::unique_ptr<OrtValue, decltype(&OrtReleaseValue)> value_x(nullptr, OrtReleaseValue); std::vector<OrtValue*> inputs(1); inputs[0] = OrtCreateTensorAsOrtValue(env, dims_x, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT); value_x.reset(inputs[0]); void* raw_data; ORT_THROW_ON_ERROR(OrtGetTensorMutableData(inputs[0], &raw_data)); memcpy(raw_data, values_x.data(), values_x.size() * sizeof(values_x[0])); std::vector<const char*> input_names{"X"}; const char* output_names[] = {"Y"}; bool is_output_allocated_by_ort = output_tensor == nullptr; OrtValue* old_output_ptr = output_tensor; ORT_THROW_ON_ERROR(OrtRun(session_object, NULL, input_names.data(), inputs.data(), inputs.size(), output_names, 1, &output_tensor)); ASSERT_NE(output_tensor, nullptr); if (!is_output_allocated_by_ort) ASSERT_EQ(output_tensor, old_output_ptr); std::unique_ptr<OrtTensorTypeAndShapeInfo> shape_info; { OrtTensorTypeAndShapeInfo* shape_info_ptr; ORT_THROW_ON_ERROR(OrtGetTensorShapeAndType(output_tensor, &shape_info_ptr)); shape_info.reset(shape_info_ptr); } size_t rtensor_dims = OrtGetNumOfDimensions(shape_info.get()); std::vector<int64_t> shape_array(rtensor_dims); OrtGetDimensions(shape_info.get(), shape_array.data(), shape_array.size()); ASSERT_EQ(shape_array, dims_y); size_t total_len = 1; for (size_t i = 0; i != rtensor_dims; ++i) { total_len *= shape_array[i]; } ASSERT_EQ(values_y.size(), total_len); float* f; ORT_THROW_ON_ERROR(OrtGetTensorMutableData(output_tensor, (void**)&f)); for (size_t i = 0; i != total_len; ++i) { ASSERT_EQ(values_y[i], f[i]); } if (is_output_allocated_by_ort) OrtReleaseValue(output_tensor); } template <typename T> void TestInference(OrtEnv* env, T model_uri, const std::vector<size_t>& dims_x, const std::vector<float>& values_x, const std::vector<int64_t>& expected_dims_y, const std::vector<float>& expected_values_y, int provider_type, bool custom_op) { SessionOptionsWrapper sf(env); if (provider_type == 1) { #ifdef USE_CUDA ORT_THROW_ON_ERROR(OrtSessionOptionsAppendExecutionProvider_CUDA(sf, 0)); std::cout << "Running simple inference with cuda provider" << std::endl; #else return; #endif } else if (provider_type == 2) { #ifdef USE_MKLDNN ORT_THROW_ON_ERROR(OrtSessionOptionsAppendExecutionProvider_Mkldnn(sf, 1)); std::cout << "Running simple inference with mkldnn provider" << std::endl; #else return; #endif } else if (provider_type == 3) { #ifdef USE_NUPHAR ORT_THROW_ON_ERROR(OrtSessionOptionsAppendExecutionProvider_Nuphar(sf, 0, "")); std::cout << "Running simple inference with nuphar provider" << std::endl; #else return; #endif } else { std::cout << "Running simple inference with default provider" << std::endl; } if (custom_op) { sf.AppendCustomOpLibPath("libonnxruntime_custom_op_shared_lib_test.so"); } std::unique_ptr<OrtSession, decltype(&OrtReleaseSession)> inference_session(sf.OrtCreateSession(model_uri), OrtReleaseSession); std::unique_ptr<MockedOrtAllocator> default_allocator(std::make_unique<MockedOrtAllocator>()); // Now run //without preallocated output tensor RunSession(default_allocator.get(), inference_session.get(), dims_x, values_x, expected_dims_y, expected_values_y, nullptr); //with preallocated output tensor std::unique_ptr<OrtValue, decltype(&OrtReleaseValue)> value_y(nullptr, OrtReleaseValue); { std::vector<OrtValue*> allocated_outputs(1); std::vector<size_t> dims_y(expected_dims_y.size()); for (size_t i = 0; i != expected_dims_y.size(); ++i) { dims_y[i] = static_cast<size_t>(expected_dims_y[i]); } allocated_outputs[0] = OrtCreateTensorAsOrtValue(default_allocator.get(), dims_y, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT); value_y.reset(allocated_outputs[0]); } //test it twice for (int i = 0; i != 2; ++i) RunSession(default_allocator.get(), inference_session.get(), dims_x, values_x, expected_dims_y, expected_values_y, value_y.get()); } static constexpr PATH_TYPE MODEL_URI = TSTR("testdata/mul_1.pb"); static constexpr PATH_TYPE CUSTOM_OP_MODEL_URI = TSTR("testdata/foo_1.pb"); class CApiTestWithProvider : public CApiTest, public ::testing::WithParamInterface<int> { }; // Tests that the Foo::Bar() method does Abc. TEST_P(CApiTestWithProvider, simple) { // simple inference test // prepare inputs std::vector<size_t> dims_x = {3, 2}; std::vector<float> values_x = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f}; // prepare expected inputs and outputs std::vector<int64_t> expected_dims_y = {3, 2}; std::vector<float> expected_values_y = {1.0f, 4.0f, 9.0f, 16.0f, 25.0f, 36.0f}; TestInference<PATH_TYPE>(env, MODEL_URI, dims_x, values_x, expected_dims_y, expected_values_y, GetParam(), false); } INSTANTIATE_TEST_CASE_P(CApiTestWithProviders, CApiTestWithProvider, ::testing::Values(0, 1, 2, 3, 4)); #ifndef _WIN32 //doesn't work, failed in type comparison TEST_F(CApiTest, DISABLED_custom_op) { std::cout << "Running custom op inference" << std::endl; std::vector<size_t> dims_x = {3, 2}; std::vector<float> values_x = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f}; // prepare expected inputs and outputs std::vector<int64_t> expected_dims_y = {3, 2}; std::vector<float> expected_values_y = {2.0f, 4.0f, 6.0f, 8.0f, 10.0f, 12.0f}; TestInference<PATH_TYPE>(env, CUSTOM_OP_MODEL_URI, dims_x, values_x, expected_dims_y, expected_values_y, false, true); } #endif #ifdef ORT_RUN_EXTERNAL_ONNX_TESTS TEST_F(CApiTest, create_session_without_session_option) { constexpr PATH_TYPE model_uri = TSTR("../models/opset8/test_squeezenet/model.onnx"); OrtSession* ret; ORT_THROW_ON_ERROR(::OrtCreateSession(env, model_uri, nullptr, &ret)); ASSERT_NE(nullptr, ret); OrtReleaseSession(ret); } #endif TEST_F(CApiTest, create_tensor) { const char* s[] = {"abc", "kmp"}; size_t expected_len = 2; std::unique_ptr<MockedOrtAllocator> default_allocator(std::make_unique<MockedOrtAllocator>()); { std::unique_ptr<OrtValue, decltype(&OrtReleaseValue)> tensor( OrtCreateTensorAsOrtValue(default_allocator.get(), {expected_len}, ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING), OrtReleaseValue); ORT_THROW_ON_ERROR(OrtFillStringTensor(tensor.get(), s, expected_len)); std::unique_ptr<OrtTensorTypeAndShapeInfo> shape_info; { OrtTensorTypeAndShapeInfo* shape_info_ptr; ORT_THROW_ON_ERROR(OrtGetTensorShapeAndType(tensor.get(), &shape_info_ptr)); shape_info.reset(shape_info_ptr); } size_t len = static_cast<size_t>(OrtGetTensorShapeElementCount(shape_info.get())); ASSERT_EQ(len, expected_len); std::vector<int64_t> shape_array(len); size_t data_len; ORT_THROW_ON_ERROR(OrtGetStringTensorDataLength(tensor.get(), &data_len)); std::string result(data_len, '\0'); std::vector<size_t> offsets(len); ORT_THROW_ON_ERROR(OrtGetStringTensorContent(tensor.get(), (void*)result.data(), data_len, offsets.data(), offsets.size())); } } TEST_F(CApiTest, create_tensor_with_data) { float values[] = {3.0f, 1.0f, 2.f, 0.f}; constexpr size_t values_length = sizeof(values) / sizeof(values[0]); OrtAllocatorInfo* info; ORT_THROW_ON_ERROR(OrtCreateAllocatorInfo("Cpu", OrtDeviceAllocator, 0, OrtMemTypeDefault, &info)); std::vector<size_t> dims = {4}; std::unique_ptr<OrtValue, decltype(&OrtReleaseValue)> tensor( OrtCreateTensorWithDataAsOrtValue(info, values, values_length * sizeof(float), dims, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT), OrtReleaseValue); OrtReleaseAllocatorInfo(info); void* new_pointer; ORT_THROW_ON_ERROR(OrtGetTensorMutableData(tensor.get(), &new_pointer)); ASSERT_EQ(new_pointer, values); struct OrtTypeInfo* type_info; ORT_THROW_ON_ERROR(OrtGetTypeInfo(tensor.get(), &type_info)); const struct OrtTensorTypeAndShapeInfo* tensor_info = OrtCastTypeInfoToTensorInfo(type_info); ASSERT_NE(tensor_info, nullptr); ASSERT_EQ(1, OrtGetNumOfDimensions(tensor_info)); OrtReleaseTypeInfo(type_info); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|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 "mitkPASpectralUnmixingFilterBase.h" // Includes for AddEnmemberMatrix #include "mitkPAPropertyCalculator.h" #include <eigen3/Eigen/Dense> // ImageAccessor #include <mitkImageReadAccessor.h> #include <mitkImageWriteAccessor.h> #include <chrono> mitk::pa::SpectralUnmixingFilterBase::SpectralUnmixingFilterBase() { this->SetNumberOfIndexedOutputs(4);// find solution --> 4 is max outputs for (unsigned int i = 0; i<GetNumberOfIndexedOutputs(); i++) { this->SetNthOutput(i, mitk::Image::New()); } m_PropertyCalculatorEigen = mitk::pa::PropertyCalculator::New(); } mitk::pa::SpectralUnmixingFilterBase::~SpectralUnmixingFilterBase() { } void mitk::pa::SpectralUnmixingFilterBase::AddWavelength(int wavelength) { m_Wavelength.push_back(wavelength); } void mitk::pa::SpectralUnmixingFilterBase::AddChromophore(mitk::pa::PropertyCalculator::ChromophoreType chromophore) { m_Chromophore.push_back(chromophore); } void mitk::pa::SpectralUnmixingFilterBase::Verbose(bool verbose) { m_Verbose = verbose; } void mitk::pa::SpectralUnmixingFilterBase::GenerateData() { MITK_INFO(m_Verbose) << "GENERATING DATA.."; mitk::Image::Pointer input = GetInput(0); unsigned int xDim = input->GetDimensions()[0]; unsigned int yDim = input->GetDimensions()[1]; unsigned int numberOfInputImages = input->GetDimensions()[2]; MITK_INFO(m_Verbose) << "x dimension: " << xDim; MITK_INFO(m_Verbose) << "y dimension: " << yDim; MITK_INFO(m_Verbose) << "z dimension: " << numberOfInputImages; unsigned int sequenceSize = m_Wavelength.size(); unsigned int totalNumberOfSequences = numberOfInputImages / sequenceSize; MITK_INFO(m_Verbose) << "TotalNumberOfSequences: " << totalNumberOfSequences; InitializeOutputs(totalNumberOfSequences); auto endmemberMatrix = CalculateEndmemberMatrix(m_Chromophore, m_Wavelength); // Copy input image into array mitk::ImageReadAccessor readAccess(input); const float* inputDataArray = ((const float*)readAccess.GetData()); CheckPreConditions(numberOfInputImages, inputDataArray); // test to see pixel values @ txt file myfile.open("SimplexNormalisation.txt"); for (unsigned int sequenceCounter = 0; sequenceCounter < totalNumberOfSequences; ++sequenceCounter) { MITK_INFO(m_Verbose) << "SequenceCounter: " << sequenceCounter; //loop over every pixel in XY-plane for (unsigned int x = 0; x < xDim; x++) { for (unsigned int y = 0; y < yDim; y++) { Eigen::VectorXf inputVector(sequenceSize); for (unsigned int z = 0; z < sequenceSize; z++) { /** * 'sequenceCounter*sequenceSize' has to be added to 'z' to ensure that one accesses the * correct pixel, because the inputDataArray contains the information of all sequences and * not just the one of the current sequence. */ unsigned int pixelNumber = (xDim*yDim*(z+sequenceCounter*sequenceSize)) + x * yDim + y; auto pixel = inputDataArray[pixelNumber]; //write all wavelength absorbtion values for one(!) pixel of a sequence to a vector inputVector[z] = pixel; } Eigen::VectorXf resultVector = SpectralUnmixingAlgorithm(endmemberMatrix, inputVector); for (int outputIdx = 0; outputIdx < GetNumberOfIndexedOutputs(); ++outputIdx) { auto output = GetOutput(outputIdx); mitk::ImageWriteAccessor writeOutput(output); float* writeBuffer = (float *)writeOutput.GetData(); writeBuffer[(xDim*yDim * sequenceCounter) + x * yDim + y] = resultVector[outputIdx]; } } } } std::chrono::steady_clock::time_point _end(std::chrono::steady_clock::now()); std::chrono::steady_clock::time_point _test(std::chrono::steady_clock::now()); MITK_INFO(m_Verbose) << "GENERATING DATA...[DONE]"; myfile.close(); } void mitk::pa::SpectralUnmixingFilterBase::CheckPreConditions(unsigned int numberOfInputImages, const float* inputDataArray) { MITK_INFO(m_Verbose) << "CHECK PRECONDITIONS ..."; if (m_Wavelength.size() < numberOfInputImages) MITK_WARN << "NUMBER OF WAVELENGTHS < NUMBER OF INPUT IMAGES"; if (m_Wavelength.size() > numberOfInputImages) mitkThrow() << "ERROR! REMOVE WAVELENGTHS!"; if (m_Chromophore.size() > m_Wavelength.size()) mitkThrow() << "ADD MORE WAVELENGTHS!"; if (typeid(inputDataArray[0]).name() != typeid(float).name()) mitkThrow() << "PIXELTYPE ERROR! FLOAT 32 REQUIRED"; MITK_INFO(m_Verbose) << "...[DONE]"; } void mitk::pa::SpectralUnmixingFilterBase::InitializeOutputs(unsigned int totalNumberOfSequences) { MITK_INFO(m_Verbose) << "Initialize Outputs ..."; unsigned int numberOfInputs = GetNumberOfIndexedInputs(); unsigned int numberOfOutputs = GetNumberOfIndexedOutputs(); MITK_INFO(m_Verbose) << "Inputs: " << numberOfInputs << " Outputs: " << numberOfOutputs; mitk::PixelType pixelType = mitk::MakeScalarPixelType<float>(); const int NUMBER_OF_SPATIAL_DIMENSIONS = 3; auto* dimensions = new unsigned int[NUMBER_OF_SPATIAL_DIMENSIONS]; for (unsigned int dimIdx = 0; dimIdx < 2; dimIdx++) { dimensions[dimIdx] = GetInput()->GetDimensions()[dimIdx]; } dimensions[2] = totalNumberOfSequences; for (unsigned int outputIdx = 0; outputIdx < numberOfOutputs; outputIdx++) GetOutput(outputIdx)->Initialize(pixelType, NUMBER_OF_SPATIAL_DIMENSIONS, dimensions); MITK_INFO(m_Verbose) << "...[DONE]"; } Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> mitk::pa::SpectralUnmixingFilterBase::CalculateEndmemberMatrix( std::vector<mitk::pa::PropertyCalculator::ChromophoreType> m_Chromophore, std::vector<int> m_Wavelength) { unsigned int numberOfChromophores = m_Chromophore.size(); //columns unsigned int numberOfWavelengths = m_Wavelength.size(); //rows Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> endmemberMatrixEigen(numberOfWavelengths, numberOfChromophores); for (unsigned int j = 0; j < numberOfChromophores; ++j) { for (unsigned int i = 0; i < numberOfWavelengths; ++i) endmemberMatrixEigen(i, j) = PropertyElement(m_Chromophore[j], m_Wavelength[i]); } MITK_INFO(m_Verbose) << "GENERATING ENMEMBERMATRIX [DONE]"; return endmemberMatrixEigen; } float mitk::pa::SpectralUnmixingFilterBase::PropertyElement(mitk::pa::PropertyCalculator::ChromophoreType chromophore, int wavelength) { if (chromophore == mitk::pa::PropertyCalculator::ChromophoreType::ONEENDMEMBER) return 1; else { float value = m_PropertyCalculatorEigen->GetAbsorptionForWavelength(chromophore, wavelength); if (value == 0) mitkThrow() << "WAVELENGTH " << wavelength << "nm NOT SUPPORTED!"; else return value; } } <commit_msg>solved 'number of output problem'.<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 "mitkPASpectralUnmixingFilterBase.h" // Includes for AddEnmemberMatrix #include "mitkPAPropertyCalculator.h" #include <eigen3/Eigen/Dense> // ImageAccessor #include <mitkImageReadAccessor.h> #include <mitkImageWriteAccessor.h> #include <chrono> mitk::pa::SpectralUnmixingFilterBase::SpectralUnmixingFilterBase() { m_PropertyCalculatorEigen = mitk::pa::PropertyCalculator::New(); } mitk::pa::SpectralUnmixingFilterBase::~SpectralUnmixingFilterBase() { } void mitk::pa::SpectralUnmixingFilterBase::AddWavelength(int wavelength) { m_Wavelength.push_back(wavelength); } void mitk::pa::SpectralUnmixingFilterBase::AddChromophore(mitk::pa::PropertyCalculator::ChromophoreType chromophore) { m_Chromophore.push_back(chromophore); } void mitk::pa::SpectralUnmixingFilterBase::Verbose(bool verbose) { m_Verbose = verbose; } void mitk::pa::SpectralUnmixingFilterBase::GenerateData() { MITK_INFO(m_Verbose) << "GENERATING DATA.."; mitk::Image::Pointer input = GetInput(0); unsigned int xDim = input->GetDimensions()[0]; unsigned int yDim = input->GetDimensions()[1]; unsigned int numberOfInputImages = input->GetDimensions()[2]; MITK_INFO(m_Verbose) << "x dimension: " << xDim; MITK_INFO(m_Verbose) << "y dimension: " << yDim; MITK_INFO(m_Verbose) << "z dimension: " << numberOfInputImages; unsigned int sequenceSize = m_Wavelength.size(); unsigned int totalNumberOfSequences = numberOfInputImages / sequenceSize; MITK_INFO(m_Verbose) << "TotalNumberOfSequences: " << totalNumberOfSequences; InitializeOutputs(totalNumberOfSequences); auto endmemberMatrix = CalculateEndmemberMatrix(m_Chromophore, m_Wavelength); // Copy input image into array mitk::ImageReadAccessor readAccess(input); const float* inputDataArray = ((const float*)readAccess.GetData()); CheckPreConditions(numberOfInputImages, inputDataArray); // test to see pixel values @ txt file myfile.open("SimplexNormalisation.txt"); for (unsigned int sequenceCounter = 0; sequenceCounter < totalNumberOfSequences; ++sequenceCounter) { MITK_INFO(m_Verbose) << "SequenceCounter: " << sequenceCounter; //loop over every pixel in XY-plane for (unsigned int x = 0; x < xDim; x++) { for (unsigned int y = 0; y < yDim; y++) { Eigen::VectorXf inputVector(sequenceSize); for (unsigned int z = 0; z < sequenceSize; z++) { /** * 'sequenceCounter*sequenceSize' has to be added to 'z' to ensure that one accesses the * correct pixel, because the inputDataArray contains the information of all sequences and * not just the one of the current sequence. */ unsigned int pixelNumber = (xDim*yDim*(z+sequenceCounter*sequenceSize)) + x * yDim + y; auto pixel = inputDataArray[pixelNumber]; //write all wavelength absorbtion values for one(!) pixel of a sequence to a vector inputVector[z] = pixel; } Eigen::VectorXf resultVector = SpectralUnmixingAlgorithm(endmemberMatrix, inputVector); for (int outputIdx = 0; outputIdx < GetNumberOfIndexedOutputs(); ++outputIdx) { auto output = GetOutput(outputIdx); mitk::ImageWriteAccessor writeOutput(output); float* writeBuffer = (float *)writeOutput.GetData(); writeBuffer[(xDim*yDim * sequenceCounter) + x * yDim + y] = resultVector[outputIdx]; } } } } std::chrono::steady_clock::time_point _end(std::chrono::steady_clock::now()); std::chrono::steady_clock::time_point _test(std::chrono::steady_clock::now()); MITK_INFO(m_Verbose) << "GENERATING DATA...[DONE]"; myfile.close(); } void mitk::pa::SpectralUnmixingFilterBase::CheckPreConditions(unsigned int numberOfInputImages, const float* inputDataArray) { MITK_INFO(m_Verbose) << "CHECK PRECONDITIONS ..."; if (m_Wavelength.size() < numberOfInputImages) MITK_WARN << "NUMBER OF WAVELENGTHS < NUMBER OF INPUT IMAGES"; if (m_Wavelength.size() > numberOfInputImages) mitkThrow() << "ERROR! REMOVE WAVELENGTHS!"; if (m_Chromophore.size() > m_Wavelength.size()) mitkThrow() << "ADD MORE WAVELENGTHS!"; if (typeid(inputDataArray[0]).name() != typeid(float).name()) mitkThrow() << "PIXELTYPE ERROR! FLOAT 32 REQUIRED"; MITK_INFO(m_Verbose) << "...[DONE]"; } void mitk::pa::SpectralUnmixingFilterBase::InitializeOutputs(unsigned int totalNumberOfSequences) { MITK_INFO(m_Verbose) << "Initialize Outputs ..."; this->SetNumberOfIndexedOutputs(m_Chromophore.size()); for (unsigned int i = 0; i<GetNumberOfIndexedOutputs(); i++) this->SetNthOutput(i, mitk::Image::New()); unsigned int numberOfInputs = GetNumberOfIndexedInputs(); unsigned int numberOfOutputs = GetNumberOfIndexedOutputs(); MITK_INFO(m_Verbose) << "Inputs: " << numberOfInputs << " Outputs: " << numberOfOutputs; mitk::PixelType pixelType = mitk::MakeScalarPixelType<float>(); const int NUMBER_OF_SPATIAL_DIMENSIONS = 3; auto* dimensions = new unsigned int[NUMBER_OF_SPATIAL_DIMENSIONS]; for (unsigned int dimIdx = 0; dimIdx < 2; dimIdx++) dimensions[dimIdx] = GetInput()->GetDimensions()[dimIdx]; dimensions[2] = totalNumberOfSequences; for (unsigned int outputIdx = 0; outputIdx < numberOfOutputs; outputIdx++) GetOutput(outputIdx)->Initialize(pixelType, NUMBER_OF_SPATIAL_DIMENSIONS, dimensions); MITK_INFO(m_Verbose) << "...[DONE]"; } Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> mitk::pa::SpectralUnmixingFilterBase::CalculateEndmemberMatrix( std::vector<mitk::pa::PropertyCalculator::ChromophoreType> m_Chromophore, std::vector<int> m_Wavelength) { unsigned int numberOfChromophores = m_Chromophore.size(); //columns unsigned int numberOfWavelengths = m_Wavelength.size(); //rows Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> endmemberMatrixEigen(numberOfWavelengths, numberOfChromophores); for (unsigned int j = 0; j < numberOfChromophores; ++j) { for (unsigned int i = 0; i < numberOfWavelengths; ++i) endmemberMatrixEigen(i, j) = PropertyElement(m_Chromophore[j], m_Wavelength[i]); } MITK_INFO(m_Verbose) << "GENERATING ENMEMBERMATRIX [DONE]"; return endmemberMatrixEigen; } float mitk::pa::SpectralUnmixingFilterBase::PropertyElement(mitk::pa::PropertyCalculator::ChromophoreType chromophore, int wavelength) { if (chromophore == mitk::pa::PropertyCalculator::ChromophoreType::ONEENDMEMBER) return 1; else { float value = m_PropertyCalculatorEigen->GetAbsorptionForWavelength(chromophore, wavelength); if (value == 0) mitkThrow() << "WAVELENGTH " << wavelength << "nm NOT SUPPORTED!"; else return value; } } <|endoftext|>
<commit_before>/** * @file IntegralImageProvider.cpp * * Implementation of class IntegralImageProvider * */ #include "IntegralImageProvider.h" IntegralImageProvider::IntegralImageProvider() {} IntegralImageProvider::~IntegralImageProvider() {} void IntegralImageProvider::execute(CameraInfo::CameraID id) { cameraID = id; makeIntegralBild(getBallDetectorIntegralImage()); } void IntegralImageProvider::makeIntegralBild( BallDetectorIntegralImage& integralImage) const { const int32_t FACTOR = integralImage.FACTOR; const uint32_t MAX_COLOR = integralImage.MAX_COLOR; const uint32_t imgWidth = getImage().width() / FACTOR; const uint32_t imgHeight = getImage().height() / FACTOR; integralImage.setDimension(imgWidth, imgHeight); uint32_t* dataPtr = integralImage.getDataPointer(); // NOTE: a pixel consists of two Y values (YUYV format). // When skipping a pixel using this pointer, you effectivly skip two Y // values. const Pixel* imgPtr = reinterpret_cast<Pixel*>(getImage().data()); const int32_t FACTOR_HALF = integralImage.FACTOR / 2; // We need to skip FACTOR-1 lines in the image after after each processed // line. The image pixels contain 2 Y values, and thus only half of the // pixels are skipped. uint32_t pixels2SkipAfterLine = (FACTOR - 1) * (imgWidth * FACTOR_HALF); // iterate over first line uint32_t* curRowPtr = dataPtr; { uint32_t akk[MAX_COLOR] = {}; for (uint16_t x = 0; x < imgWidth; ++x) { if (getFieldColorPercept().greenHSISeparator.isColor(*imgPtr)) { ++akk[1]; } else { akk[0] += (imgPtr->y0); } for (uint16_t i = 0; i < MAX_COLOR; ++i) { curRowPtr[i] = akk[i]; } // Increment current row by one step curRowPtr += MAX_COLOR; // The image pointer needs to skip 4 Y values == 2 image pixels imgPtr += FACTOR_HALF; } } imgPtr += pixels2SkipAfterLine; // set a pointer to the start of the first line uint32_t* prevRowPtr = dataPtr; // iterate over all remaining lines using the previously accumulated values for (uint16_t y = 1; y < imgHeight; ++y) { // reset accumalator in each line uint32_t akk[MAX_COLOR] = {}; for (uint16_t x = 0; x < imgWidth; ++x) { if (getFieldColorPercept().greenHSISeparator.isColor(*imgPtr)) { ++akk[1]; } else { akk[0] += (imgPtr->y0); } for (uint16_t i = 0; i < MAX_COLOR; ++i) { curRowPtr[i] = akk[i] + prevRowPtr[i]; } // Both the current row and the previous row are incremented by one // step curRowPtr += MAX_COLOR; prevRowPtr += MAX_COLOR; // The image pointer needs to skip 4 Y values == 2 image pixels imgPtr += FACTOR_HALF; } imgPtr += pixels2SkipAfterLine; } }<commit_msg>formatting<commit_after>/** * @file IntegralImageProvider.cpp * * Implementation of class IntegralImageProvider * */ #include "IntegralImageProvider.h" IntegralImageProvider::IntegralImageProvider() {} IntegralImageProvider::~IntegralImageProvider() {} void IntegralImageProvider::execute(CameraInfo::CameraID id) { cameraID = id; makeIntegralBild(getBallDetectorIntegralImage()); } void IntegralImageProvider::makeIntegralBild(BallDetectorIntegralImage& integralImage) const { const int32_t FACTOR = integralImage.FACTOR; const uint32_t MAX_COLOR = integralImage.MAX_COLOR; const uint32_t imgWidth = getImage().width() / FACTOR; const uint32_t imgHeight = getImage().height() / FACTOR; integralImage.setDimension(imgWidth, imgHeight); uint32_t* dataPtr = integralImage.getDataPointer(); // NOTE: a pixel consists of two Y values (YUYV format). // When skipping a pixel using this pointer, you effectivly skip two Y // values. const Pixel* imgPtr = reinterpret_cast<Pixel*>(getImage().data()); const int32_t FACTOR_HALF = integralImage.FACTOR / 2; // We need to skip FACTOR-1 lines in the image after after each processed // line. The image pixels contain 2 Y values, and thus only half of the // pixels are skipped. uint32_t pixels2SkipAfterLine = (FACTOR - 1) * (imgWidth * FACTOR_HALF); // iterate over first line uint32_t* curRowPtr = dataPtr; { uint32_t akk[MAX_COLOR] = {}; for (uint16_t x = 0; x < imgWidth; ++x) { if (getFieldColorPercept().greenHSISeparator.isColor(*imgPtr)) { ++akk[1]; } else { akk[0] += (imgPtr->y0); } for (uint16_t i = 0; i < MAX_COLOR; ++i) { curRowPtr[i] = akk[i]; } // Increment current row by one step curRowPtr += MAX_COLOR; // The image pointer needs to skip 4 Y values == 2 image pixels imgPtr += FACTOR_HALF; } } imgPtr += pixels2SkipAfterLine; // set a pointer to the start of the first line uint32_t* prevRowPtr = dataPtr; // iterate over all remaining lines using the previously accumulated values for (uint16_t y = 1; y < imgHeight; ++y) { // reset accumalator in each line uint32_t akk[MAX_COLOR] = {}; for (uint16_t x = 0; x < imgWidth; ++x) { if (getFieldColorPercept().greenHSISeparator.isColor(*imgPtr)) { ++akk[1]; } else { akk[0] += (imgPtr->y0); } for (uint16_t i = 0; i < MAX_COLOR; ++i) { curRowPtr[i] = akk[i] + prevRowPtr[i]; } // Both the current row and the previous row are incremented by one // step curRowPtr += MAX_COLOR; prevRowPtr += MAX_COLOR; // The image pointer needs to skip 4 Y values == 2 image pixels imgPtr += FACTOR_HALF; } imgPtr += pixels2SkipAfterLine; } }<|endoftext|>
<commit_before><commit_msg>Copy parsed URL into CF_UNICODETEXT when user select entire of Omnibox.<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_webrequest_api.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/login/login_prompt.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/ui_test_utils.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" #include "net/base/mock_host_resolver.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h" namespace { class CancelLoginDialog : public content::NotificationObserver { public: CancelLoginDialog() { registrar_.Add(this, chrome::NOTIFICATION_AUTH_NEEDED, content::NotificationService::AllSources()); } virtual ~CancelLoginDialog() {} virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { LoginHandler* handler = content::Details<LoginNotificationDetails>(details).ptr()->handler(); handler->CancelAuth(); } private: content::NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(CancelLoginDialog); }; } // namespace class ExtensionWebRequestApiTest : public ExtensionApiTest { public: virtual void SetUpInProcessBrowserTestFixture() { ExtensionApiTest::SetUpInProcessBrowserTestFixture(); host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); } }; IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestApi) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_api.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestSimple) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_simple.html")) << message_; } // Broken, http://crbug.com/101651 IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, DISABLED_WebRequestComplex) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_complex.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestAuthRequired) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); CancelLoginDialog login_dialog_helper; ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_auth_required.html")) << message_; } // Hangs flakily: http://crbug.com/91715 IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, DISABLED_WebRequestBlocking) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_blocking.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestNewTab) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); // Wait for the extension to set itself up and return control to us. ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_newTab.html")) << message_; ResultCatcher catcher; ExtensionService* service = browser()->profile()->GetExtensionService(); const Extension* extension = service->GetExtensionById(last_loaded_extension_id_, false); GURL url = extension->GetResourceURL("newTab/a.html"); ui_test_utils::NavigateToURL(browser(), url); // There's a link on a.html with target=_blank. Click on it to open it in a // new tab. WebKit::WebMouseEvent mouse_event; mouse_event.type = WebKit::WebInputEvent::MouseDown; mouse_event.button = WebKit::WebMouseEvent::ButtonLeft; mouse_event.x = 7; mouse_event.y = 7; mouse_event.clickCount = 1; TabContents* tab = browser()->GetSelectedTabContents(); tab->render_view_host()->ForwardMouseEvent(mouse_event); mouse_event.type = WebKit::WebInputEvent::MouseUp; tab->render_view_host()->ForwardMouseEvent(mouse_event); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } <commit_msg>Make sure that the about:blank tab is loaded after returning from the extension<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_webrequest_api.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/login/login_prompt.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/ui_test_utils.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" #include "net/base/mock_host_resolver.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h" namespace { class CancelLoginDialog : public content::NotificationObserver { public: CancelLoginDialog() { registrar_.Add(this, chrome::NOTIFICATION_AUTH_NEEDED, content::NotificationService::AllSources()); } virtual ~CancelLoginDialog() {} virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { LoginHandler* handler = content::Details<LoginNotificationDetails>(details).ptr()->handler(); handler->CancelAuth(); } private: content::NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(CancelLoginDialog); }; } // namespace class ExtensionWebRequestApiTest : public ExtensionApiTest { public: virtual void SetUpInProcessBrowserTestFixture() { ExtensionApiTest::SetUpInProcessBrowserTestFixture(); host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); } }; IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestApi) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_api.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestSimple) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_simple.html")) << message_; } // Broken, http://crbug.com/101651 IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, DISABLED_WebRequestComplex) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_complex.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestAuthRequired) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); CancelLoginDialog login_dialog_helper; ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_auth_required.html")) << message_; } // Hangs flakily: http://crbug.com/91715 IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, DISABLED_WebRequestBlocking) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_blocking.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestNewTab) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); // Wait for the extension to set itself up and return control to us. ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_newTab.html")) << message_; TabContents* tab = browser()->GetSelectedTabContents(); ui_test_utils::WaitForLoadStop(tab); ResultCatcher catcher; ExtensionService* service = browser()->profile()->GetExtensionService(); const Extension* extension = service->GetExtensionById(last_loaded_extension_id_, false); GURL url = extension->GetResourceURL("newTab/a.html"); ui_test_utils::NavigateToURL(browser(), url); // There's a link on a.html with target=_blank. Click on it to open it in a // new tab. WebKit::WebMouseEvent mouse_event; mouse_event.type = WebKit::WebInputEvent::MouseDown; mouse_event.button = WebKit::WebMouseEvent::ButtonLeft; mouse_event.x = 7; mouse_event.y = 7; mouse_event.clickCount = 1; tab->render_view_host()->ForwardMouseEvent(mouse_event); mouse_event.type = WebKit::WebInputEvent::MouseUp; tab->render_view_host()->ForwardMouseEvent(mouse_event); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/autofill_messages.h" #include "chrome/test/render_view_test.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebFormElement.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebString.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebURLError.h" #include "webkit/glue/form_data.h" #include "webkit/glue/web_io_operators.h" using webkit_glue::FormData; using WebKit::WebFrame; using WebKit::WebString; using WebKit::WebTextDirection; using WebKit::WebURLError; typedef RenderViewTest FormAutocompleteTest; // Tests that submitting a form generates a FormSubmitted message // with the form fields. TEST_F(FormAutocompleteTest, NormalFormSubmit) { // Load a form. LoadHTML("<html><form id='myForm'><input name='fname' value='Rick'/>" "<input name='lname' value='Deckard'/></form></html>"); // Submit the form. ExecuteJavaScript("document.getElementById('myForm').submit();"); ProcessPendingMessages(); const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching( AutofillHostMsg_FormSubmitted::ID); ASSERT_TRUE(message != NULL); Tuple1<FormData> forms; AutofillHostMsg_FormSubmitted::Read(message, &forms); ASSERT_EQ(2U, forms.a.fields.size()); webkit_glue::FormField& form_field = forms.a.fields[0]; EXPECT_EQ(WebString("fname"), form_field.name); EXPECT_EQ(WebString("Rick"), form_field.value); form_field = forms.a.fields[1]; EXPECT_EQ(WebString("lname"), form_field.name); EXPECT_EQ(WebString("Deckard"), form_field.value); } // Tests that submitting a form that has autocomplete="off" does not generate a // FormSubmitted message. TEST_F(FormAutocompleteTest, AutoCompleteOffFormSubmit) { // Load a form. LoadHTML("<html><form id='myForm' autocomplete='off'>" "<input name='fname' value='Rick'/>" "<input name='lname' value='Deckard'/>" "</form></html>"); // Submit the form. ExecuteJavaScript("document.getElementById('myForm').submit();"); ProcessPendingMessages(); // No FormSubmitted message should have been sent. EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching( AutofillHostMsg_FormSubmitted::ID)); } // Tests that fields with autocomplete off are not submitted. TEST_F(FormAutocompleteTest, AutoCompleteOffInputSubmit) { // Load a form. LoadHTML("<html><form id='myForm'>" "<input name='fname' value='Rick'/>" "<input name='lname' value='Deckard' autocomplete='off'/>" "</form></html>"); // Submit the form. ExecuteJavaScript("document.getElementById('myForm').submit();"); ProcessPendingMessages(); // No FormSubmitted message should have been sent. const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching( AutofillHostMsg_FormSubmitted::ID); ASSERT_TRUE(message != NULL); Tuple1<FormData> forms; AutofillHostMsg_FormSubmitted::Read(message, &forms); ASSERT_EQ(1U, forms.a.fields.size()); webkit_glue::FormField& form_field = forms.a.fields[0]; EXPECT_EQ(WebString("fname"), form_field.name); EXPECT_EQ(WebString("Rick"), form_field.value); } // Tests that submitting a form that has been dynamically set as autocomplete // off does not generate a FormSubmitted message. // http://crbug.com/36520 // TODO(jcampan): Waiting on WebKit bug 35823. TEST_F(FormAutocompleteTest, FAILS_DynamicAutoCompleteOffFormSubmit) { LoadHTML("<html><form id='myForm'><input name='fname' value='Rick'/>" "<input name='lname' value='Deckard'/></form></html>"); WebKit::WebElement element = GetMainFrame()->document().getElementById(WebKit::WebString("myForm")); ASSERT_FALSE(element.isNull()); WebKit::WebFormElement form = element.to<WebKit::WebFormElement>(); EXPECT_TRUE(form.autoComplete()); // Dynamically mark the form as autocomplete off. ExecuteJavaScript("document.getElementById('myForm').autocomplete='off';"); ProcessPendingMessages(); EXPECT_FALSE(form.autoComplete()); // Submit the form. ExecuteJavaScript("document.getElementById('myForm').submit();"); ProcessPendingMessages(); // No FormSubmitted message should have been sent. EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching( AutofillHostMsg_FormSubmitted::ID)); } <commit_msg>Fix failing autofill test<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/autofill_messages.h" #include "chrome/test/render_view_test.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebFormElement.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebString.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebURLError.h" #include "webkit/glue/form_data.h" #include "webkit/glue/web_io_operators.h" using webkit_glue::FormData; using WebKit::WebFrame; using WebKit::WebString; using WebKit::WebTextDirection; using WebKit::WebURLError; typedef RenderViewTest FormAutocompleteTest; // Tests that submitting a form generates a FormSubmitted message // with the form fields. TEST_F(FormAutocompleteTest, NormalFormSubmit) { // Load a form. LoadHTML("<html><form id='myForm'><input name='fname' value='Rick'/>" "<input name='lname' value='Deckard'/></form></html>"); // Submit the form. ExecuteJavaScript("document.getElementById('myForm').submit();"); ProcessPendingMessages(); const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching( AutofillHostMsg_FormSubmitted::ID); ASSERT_TRUE(message != NULL); Tuple1<FormData> forms; AutofillHostMsg_FormSubmitted::Read(message, &forms); ASSERT_EQ(2U, forms.a.fields.size()); webkit_glue::FormField& form_field = forms.a.fields[0]; EXPECT_EQ(WebString("fname"), form_field.name); EXPECT_EQ(WebString("Rick"), form_field.value); form_field = forms.a.fields[1]; EXPECT_EQ(WebString("lname"), form_field.name); EXPECT_EQ(WebString("Deckard"), form_field.value); } // Tests that submitting a form that has autocomplete="off" does not generate a // FormSubmitted message. TEST_F(FormAutocompleteTest, AutoCompleteOffFormSubmit) { // Load a form. LoadHTML("<html><form id='myForm' autocomplete='off'>" "<input name='fname' value='Rick'/>" "<input name='lname' value='Deckard'/>" "</form></html>"); // Submit the form. ExecuteJavaScript("document.getElementById('myForm').submit();"); ProcessPendingMessages(); // No FormSubmitted message should have been sent. EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching( AutofillHostMsg_FormSubmitted::ID)); } // Tests that fields with autocomplete off are not submitted. TEST_F(FormAutocompleteTest, AutoCompleteOffInputSubmit) { // Load a form. LoadHTML("<html><form id='myForm'>" "<input name='fname' value='Rick'/>" "<input name='lname' value='Deckard' autocomplete='off'/>" "</form></html>"); // Submit the form. ExecuteJavaScript("document.getElementById('myForm').submit();"); ProcessPendingMessages(); // No FormSubmitted message should have been sent. const IPC::Message* message = render_thread_.sink().GetFirstMessageMatching( AutofillHostMsg_FormSubmitted::ID); ASSERT_TRUE(message != NULL); Tuple1<FormData> forms; AutofillHostMsg_FormSubmitted::Read(message, &forms); ASSERT_EQ(1U, forms.a.fields.size()); webkit_glue::FormField& form_field = forms.a.fields[0]; EXPECT_EQ(WebString("fname"), form_field.name); EXPECT_EQ(WebString("Rick"), form_field.value); } // Tests that submitting a form that has been dynamically set as autocomplete // off does not generate a FormSubmitted message. // http://crbug.com/36520 TEST_F(FormAutocompleteTest, DynamicAutoCompleteOffFormSubmit) { LoadHTML("<html><form id='myForm'><input name='fname' value='Rick'/>" "<input name='lname' value='Deckard'/></form></html>"); WebKit::WebElement element = GetMainFrame()->document().getElementById(WebKit::WebString("myForm")); ASSERT_FALSE(element.isNull()); WebKit::WebFormElement form = element.to<WebKit::WebFormElement>(); EXPECT_TRUE(form.autoComplete()); // Dynamically mark the form as autocomplete off. ExecuteJavaScript("document.getElementById('myForm')." "setAttribute('autocomplete', 'off');"); ProcessPendingMessages(); EXPECT_FALSE(form.autoComplete()); // Submit the form. ExecuteJavaScript("document.getElementById('myForm').submit();"); ProcessPendingMessages(); // No FormSubmitted message should have been sent. EXPECT_FALSE(render_thread_.sink().GetFirstMessageMatching( AutofillHostMsg_FormSubmitted::ID)); } <|endoftext|>
<commit_before><commit_msg>Add wrong surface warnings to NavigationMesh.create_from_mesh()<commit_after><|endoftext|>
<commit_before><commit_msg>INTEGRATION: CWS impress2 (1.1.2); FILE ADDED 2004/06/08 12:42:00 af 1.1.2.1: #i22705# Initial revision.<commit_after><|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the plugins of the Qt Toolkit. ** ** $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 <private/qgraphicssystemplugin_p.h> #include <private/qgraphicssystem_gl_p.h> #include <qgl.h> QT_BEGIN_NAMESPACE class QGLGraphicsSystemPlugin : public QGraphicsSystemPlugin { public: QStringList keys() const; QGraphicsSystem *create(const QString&); }; QStringList QGLGraphicsSystemPlugin::keys() const { QStringList list; list << QLatin1String("OpenGL") << QLatin1String("OpenGL1"); return list; } QGraphicsSystem* QGLGraphicsSystemPlugin::create(const QString& system) { if (system.toLower() == QLatin1String("opengl1")) { QGL::setPreferredPaintEngine(QPaintEngine::OpenGL); return new QGLGraphicsSystem; } if (system.toLower() == QLatin1String("opengl")) return new QGLGraphicsSystem; return 0; } Q_EXPORT_PLUGIN2(opengl, QGLGraphicsSystemPlugin) QT_END_NAMESPACE <commit_msg>Add "opengl2" as an option for creating an OpenGL graphics system<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the plugins of the Qt Toolkit. ** ** $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 <private/qgraphicssystemplugin_p.h> #include <private/qgraphicssystem_gl_p.h> #include <qgl.h> QT_BEGIN_NAMESPACE class QGLGraphicsSystemPlugin : public QGraphicsSystemPlugin { public: QStringList keys() const; QGraphicsSystem *create(const QString&); }; QStringList QGLGraphicsSystemPlugin::keys() const { QStringList list; list << QLatin1String("OpenGL") << QLatin1String("OpenGL1"); #if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) list << QLatin1String("OpenGL2"); #endif return list; } QGraphicsSystem* QGLGraphicsSystemPlugin::create(const QString& system) { if (system.toLower() == QLatin1String("opengl1")) { QGL::setPreferredPaintEngine(QPaintEngine::OpenGL); return new QGLGraphicsSystem; } #if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) if (system.toLower() == QLatin1String("opengl2")) { QGL::setPreferredPaintEngine(QPaintEngine::OpenGL2); return new QGLGraphicsSystem; } #endif if (system.toLower() == QLatin1String("opengl")) return new QGLGraphicsSystem; return 0; } Q_EXPORT_PLUGIN2(opengl, QGLGraphicsSystemPlugin) QT_END_NAMESPACE <|endoftext|>
<commit_before>#include "shortcutmanager.h" #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/actioncontainer.h> #include <coreplugin/icore.h> #include <coreplugin/editormanager/documentmodel.h> #include <coreplugin/coreconstants.h> #include <utils/hostosinfo.h> #include "qmldesignerconstants.h" #include "qmldesignerplugin.h" #include "designmodewidget.h" namespace QmlDesigner { ShortCutManager::ShortCutManager() : QObject(), m_revertToSavedAction(0), m_saveAction(0), m_saveAsAction(0), m_closeCurrentEditorAction(0), m_closeAllEditorsAction(0), m_closeOtherEditorsAction(0), m_undoAction(tr("&Undo"), 0), m_redoAction(tr("&Redo"), 0), m_deleteAction(tr("Delete"), tr("Delete \"%1\""), Utils::ParameterAction::EnabledWithParameter), m_cutAction(tr("Cu&t"), tr("Cut \"%1\""), Utils::ParameterAction::EnabledWithParameter), m_copyAction(tr("&Copy"), tr("Copy \"%1\""), Utils::ParameterAction::EnabledWithParameter), m_pasteAction(tr("&Paste"), tr("Paste \"%1\""), Utils::ParameterAction::EnabledWithParameter), m_selectAllAction(tr("Select &All"), tr("Select All \"%1\""), Utils::ParameterAction::EnabledWithParameter), m_hideSidebarsAction(tr("Toggle Full Screen"), 0), m_restoreDefaultViewAction(tr("&Restore Default View"), 0), m_toggleLeftSidebarAction(tr("Toggle &Left Sidebar"), 0), m_toggleRightSidebarAction(tr("Toggle &Right Sidebar"), 0), m_goIntoComponentAction (tr("&Go into Component"), 0) { } void ShortCutManager::registerActions(const Core::Context &qmlDesignerMainContext, const Core::Context &qmlDesignerFormEditorContext, const Core::Context &qmlDesignerNavigatorContext) { Core::ActionContainer *editMenu = Core::ActionManager::actionContainer(Core::Constants::M_EDIT); connect(&m_undoAction, SIGNAL(triggered()), this, SLOT(undo())); connect(&m_redoAction, SIGNAL(triggered()), this, SLOT(redo())); connect(&m_deleteAction, SIGNAL(triggered()), this, SLOT(deleteSelected())); connect(&m_cutAction, SIGNAL(triggered()), this, SLOT(cutSelected())); connect(&m_copyAction, SIGNAL(triggered()), this, SLOT(copySelected())); connect(&m_pasteAction, SIGNAL(triggered()), this, SLOT(paste())); connect(&m_selectAllAction, SIGNAL(triggered()), this, SLOT(selectAll())); connect(&m_hideSidebarsAction, SIGNAL(triggered()), this, SLOT(toggleSidebars())); connect(&m_restoreDefaultViewAction, SIGNAL(triggered()), QmlDesignerPlugin::instance()->mainWidget(), SLOT(restoreDefaultView())); connect(&m_goIntoComponentAction, SIGNAL(triggered()), SLOT(goIntoComponent())); connect(&m_toggleLeftSidebarAction, SIGNAL(triggered()), QmlDesignerPlugin::instance()->mainWidget(), SLOT(toggleLeftSidebar())); connect(&m_toggleRightSidebarAction, SIGNAL(triggered()), QmlDesignerPlugin::instance()->mainWidget(), SLOT(toggleRightSidebar())); // Revert to saved QObject *em = Core::EditorManager::instance(); Core::ActionManager::registerAction(&m_revertToSavedAction,Core::Constants::REVERTTOSAVED, qmlDesignerMainContext); connect(&m_revertToSavedAction, SIGNAL(triggered()), em, SLOT(revertToSaved())); //Save Core::ActionManager::registerAction(&m_saveAction, Core::Constants::SAVE, qmlDesignerMainContext); connect(&m_saveAction, SIGNAL(triggered()), em, SLOT(saveDocument())); //Save As Core::ActionManager::registerAction(&m_saveAsAction, Core::Constants::SAVEAS, qmlDesignerMainContext); connect(&m_saveAsAction, SIGNAL(triggered()), em, SLOT(saveDocumentAs())); //Close Editor Core::ActionManager::registerAction(&m_closeCurrentEditorAction, Core::Constants::CLOSE, qmlDesignerMainContext); connect(&m_closeCurrentEditorAction, SIGNAL(triggered()), em, SLOT(closeEditor())); //Close All Core::ActionManager::registerAction(&m_closeAllEditorsAction, Core::Constants::CLOSEALL, qmlDesignerMainContext); connect(&m_closeAllEditorsAction, SIGNAL(triggered()), em, SLOT(closeAllEditors())); //Close All Others Action Core::ActionManager::registerAction(&m_closeOtherEditorsAction, Core::Constants::CLOSEOTHERS, qmlDesignerMainContext); connect(&m_closeOtherEditorsAction, SIGNAL(triggered()), em, SLOT(closeOtherEditors())); // Undo / Redo Core::ActionManager::registerAction(&m_undoAction, Core::Constants::UNDO, qmlDesignerMainContext); Core::ActionManager::registerAction(&m_redoAction, Core::Constants::REDO, qmlDesignerMainContext); Core::Command *command; //GoIntoComponent command = Core::ActionManager::registerAction(&m_goIntoComponentAction, Constants::GO_INTO_COMPONENT, qmlDesignerMainContext); command->setDefaultKeySequence(QKeySequence(Qt::Key_F2)); //Edit Menu command = Core::ActionManager::registerAction(&m_deleteAction, QmlDesigner::Constants::C_DELETE, qmlDesignerFormEditorContext); command = Core::ActionManager::registerAction(&m_deleteAction, QmlDesigner::Constants::C_DELETE, qmlDesignerNavigatorContext); command->setDefaultKeySequence(QKeySequence::Delete); command->setAttribute(Core::Command::CA_Hide); // don't show delete in other modes editMenu->addAction(command, Core::Constants::G_EDIT_COPYPASTE); command = Core::ActionManager::registerAction(&m_cutAction, Core::Constants::CUT, qmlDesignerFormEditorContext); command = Core::ActionManager::registerAction(&m_cutAction, Core::Constants::CUT, qmlDesignerNavigatorContext); command->setDefaultKeySequence(QKeySequence::Cut); editMenu->addAction(command, Core::Constants::G_EDIT_COPYPASTE); command = Core::ActionManager::registerAction(&m_copyAction, Core::Constants::COPY, qmlDesignerFormEditorContext); command = Core::ActionManager::registerAction(&m_copyAction, Core::Constants::COPY, qmlDesignerNavigatorContext); command->setDefaultKeySequence(QKeySequence::Copy); editMenu->addAction(command, Core::Constants::G_EDIT_COPYPASTE); command = Core::ActionManager::registerAction(&m_pasteAction, Core::Constants::PASTE, qmlDesignerFormEditorContext); command = Core::ActionManager::registerAction(&m_pasteAction, Core::Constants::PASTE, qmlDesignerNavigatorContext); command->setDefaultKeySequence(QKeySequence::Paste); editMenu->addAction(command, Core::Constants::G_EDIT_COPYPASTE); command = Core::ActionManager::registerAction(&m_selectAllAction, Core::Constants::SELECTALL, qmlDesignerFormEditorContext); command = Core::ActionManager::registerAction(&m_selectAllAction, Core::Constants::SELECTALL, qmlDesignerNavigatorContext); command->setDefaultKeySequence(QKeySequence::SelectAll); editMenu->addAction(command, Core::Constants::G_EDIT_SELECTALL); Core::ActionContainer *viewsMenu = Core::ActionManager::actionContainer(Core::Constants::M_WINDOW_VIEWS); command = Core::ActionManager::registerAction(&m_toggleLeftSidebarAction, Constants::TOGGLE_LEFT_SIDEBAR, qmlDesignerMainContext); command->setAttribute(Core::Command::CA_Hide); command->setDefaultKeySequence(QKeySequence("Ctrl+Alt+0")); viewsMenu->addAction(command); command = Core::ActionManager::registerAction(&m_toggleRightSidebarAction, Constants::TOGGLE_RIGHT_SIDEBAR, qmlDesignerMainContext); command->setAttribute(Core::Command::CA_Hide); command->setDefaultKeySequence(QKeySequence("Ctrl+Alt+Shift+0")); viewsMenu->addAction(command); command = Core::ActionManager::registerAction(&m_restoreDefaultViewAction, Constants::RESTORE_DEFAULT_VIEW, qmlDesignerMainContext); command->setAttribute(Core::Command::CA_Hide); viewsMenu->addAction(command); command = Core::ActionManager::registerAction(&m_hideSidebarsAction, Core::Constants::TOGGLE_SIDEBAR, qmlDesignerMainContext); if (Utils::HostOsInfo::isMacHost()) { // add second shortcut to trigger delete QAction *deleteAction = new QAction(this); deleteAction->setShortcut(QKeySequence(QLatin1String("Backspace"))); connect(deleteAction, SIGNAL(triggered()), &m_deleteAction, SIGNAL(triggered())); } } void ShortCutManager::updateActions(Core::IEditor* currentEditor) { int openedCount = Core::EditorManager::documentModel()->documentCount(); m_saveAction.setEnabled(currentEditor != 0 && currentEditor->document()->isModified()); m_saveAsAction.setEnabled(currentEditor != 0 && currentEditor->document()->isSaveAsAllowed()); m_revertToSavedAction.setEnabled(currentEditor != 0 && !currentEditor->document()->filePath().isEmpty() && currentEditor->document()->isModified()); QString quotedName; if (currentEditor) quotedName = '"' + currentEditor->document()->displayName() + '"'; m_saveAsAction.setText(tr("Save %1 As...").arg(quotedName)); m_saveAction.setText(tr("&Save %1").arg(quotedName)); m_revertToSavedAction.setText(tr("Revert %1 to Saved").arg(quotedName)); m_closeCurrentEditorAction.setEnabled(currentEditor != 0); m_closeCurrentEditorAction.setText(tr("Close %1").arg(quotedName)); m_closeAllEditorsAction.setEnabled(openedCount > 0); m_closeOtherEditorsAction.setEnabled(openedCount > 1); m_closeOtherEditorsAction.setText((openedCount > 1 ? tr("Close All Except %1").arg(quotedName) : tr("Close Others"))); } void ShortCutManager::undo() { if (currentDesignDocument()) currentDesignDocument()->undo(); } void ShortCutManager::redo() { if (currentDesignDocument()) currentDesignDocument()->redo(); } void ShortCutManager::deleteSelected() { if (currentDesignDocument()) currentDesignDocument()->deleteSelected(); } void ShortCutManager::cutSelected() { if (currentDesignDocument()) currentDesignDocument()->cutSelected(); } void ShortCutManager::copySelected() { if (currentDesignDocument()) currentDesignDocument()->copySelected(); } void ShortCutManager::paste() { if (currentDesignDocument()) currentDesignDocument()->paste(); } void ShortCutManager::selectAll() { if (currentDesignDocument()) currentDesignDocument()->selectAll(); } void ShortCutManager::toggleSidebars() { QmlDesignerPlugin::instance()->mainWidget()->toggleSidebars(); } void ShortCutManager::toggleLeftSidebar() { QmlDesignerPlugin::instance()->mainWidget()->toggleLeftSidebar(); } void ShortCutManager::toggleRightSidebar() { QmlDesignerPlugin::instance()->mainWidget()->toggleRightSidebar(); } void ShortCutManager::connectUndoActions(DesignDocument *designDocument) { if (designDocument) { connect(designDocument, SIGNAL(undoAvailable(bool)), this, SLOT(undoAvailable(bool))); connect(designDocument, SIGNAL(redoAvailable(bool)), this, SLOT(redoAvailable(bool))); } } void ShortCutManager::disconnectUndoActions(DesignDocument *designDocument) { if (currentDesignDocument()) { disconnect(designDocument, SIGNAL(undoAvailable(bool)), this, SLOT(undoAvailable(bool))); disconnect(designDocument, SIGNAL(redoAvailable(bool)), this, SLOT(redoAvailable(bool))); } } void ShortCutManager::updateUndoActions(DesignDocument *designDocument) { if (designDocument) { m_undoAction.setEnabled(designDocument->isUndoAvailable()); m_redoAction.setEnabled(designDocument->isRedoAvailable()); } else { m_undoAction.setEnabled(false); m_redoAction.setEnabled(false); } } DesignDocument *ShortCutManager::currentDesignDocument() const { return QmlDesignerPlugin::instance()->currentDesignDocument(); } void ShortCutManager::undoAvailable(bool isAvailable) { DesignDocument *documentController = qobject_cast<DesignDocument*>(sender()); if (currentDesignDocument() && currentDesignDocument() == documentController) { m_undoAction.setEnabled(isAvailable); } } void ShortCutManager::redoAvailable(bool isAvailable) { DesignDocument *documentController = qobject_cast<DesignDocument*>(sender()); if (currentDesignDocument() && currentDesignDocument() == documentController) { m_redoAction.setEnabled(isAvailable); } } void ShortCutManager::goIntoComponent() { if (currentDesignDocument() && currentDesignDocument()->currentModel() && currentDesignDocument()->rewriterView() && currentDesignDocument()->rewriterView()->hasSingleSelectedModelNode()) { DocumentManager::goIntoComponent(currentDesignDocument()->rewriterView()->singleSelectedModelNode()); } } } // namespace QmlDesigner <commit_msg>QmlDesigner: Change Full Screen in Sidebars<commit_after>#include "shortcutmanager.h" #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/actioncontainer.h> #include <coreplugin/icore.h> #include <coreplugin/editormanager/documentmodel.h> #include <coreplugin/coreconstants.h> #include <utils/hostosinfo.h> #include "qmldesignerconstants.h" #include "qmldesignerplugin.h" #include "designmodewidget.h" namespace QmlDesigner { ShortCutManager::ShortCutManager() : QObject(), m_revertToSavedAction(0), m_saveAction(0), m_saveAsAction(0), m_closeCurrentEditorAction(0), m_closeAllEditorsAction(0), m_closeOtherEditorsAction(0), m_undoAction(tr("&Undo"), 0), m_redoAction(tr("&Redo"), 0), m_deleteAction(tr("Delete"), tr("Delete \"%1\""), Utils::ParameterAction::EnabledWithParameter), m_cutAction(tr("Cu&t"), tr("Cut \"%1\""), Utils::ParameterAction::EnabledWithParameter), m_copyAction(tr("&Copy"), tr("Copy \"%1\""), Utils::ParameterAction::EnabledWithParameter), m_pasteAction(tr("&Paste"), tr("Paste \"%1\""), Utils::ParameterAction::EnabledWithParameter), m_selectAllAction(tr("Select &All"), tr("Select All \"%1\""), Utils::ParameterAction::EnabledWithParameter), m_hideSidebarsAction(tr("Toggle Sidebars"), 0), m_restoreDefaultViewAction(tr("&Restore Default View"), 0), m_toggleLeftSidebarAction(tr("Toggle &Left Sidebar"), 0), m_toggleRightSidebarAction(tr("Toggle &Right Sidebar"), 0), m_goIntoComponentAction (tr("&Go into Component"), 0) { } void ShortCutManager::registerActions(const Core::Context &qmlDesignerMainContext, const Core::Context &qmlDesignerFormEditorContext, const Core::Context &qmlDesignerNavigatorContext) { Core::ActionContainer *editMenu = Core::ActionManager::actionContainer(Core::Constants::M_EDIT); connect(&m_undoAction, SIGNAL(triggered()), this, SLOT(undo())); connect(&m_redoAction, SIGNAL(triggered()), this, SLOT(redo())); connect(&m_deleteAction, SIGNAL(triggered()), this, SLOT(deleteSelected())); connect(&m_cutAction, SIGNAL(triggered()), this, SLOT(cutSelected())); connect(&m_copyAction, SIGNAL(triggered()), this, SLOT(copySelected())); connect(&m_pasteAction, SIGNAL(triggered()), this, SLOT(paste())); connect(&m_selectAllAction, SIGNAL(triggered()), this, SLOT(selectAll())); connect(&m_hideSidebarsAction, SIGNAL(triggered()), this, SLOT(toggleSidebars())); connect(&m_restoreDefaultViewAction, SIGNAL(triggered()), QmlDesignerPlugin::instance()->mainWidget(), SLOT(restoreDefaultView())); connect(&m_goIntoComponentAction, SIGNAL(triggered()), SLOT(goIntoComponent())); connect(&m_toggleLeftSidebarAction, SIGNAL(triggered()), QmlDesignerPlugin::instance()->mainWidget(), SLOT(toggleLeftSidebar())); connect(&m_toggleRightSidebarAction, SIGNAL(triggered()), QmlDesignerPlugin::instance()->mainWidget(), SLOT(toggleRightSidebar())); // Revert to saved QObject *em = Core::EditorManager::instance(); Core::ActionManager::registerAction(&m_revertToSavedAction,Core::Constants::REVERTTOSAVED, qmlDesignerMainContext); connect(&m_revertToSavedAction, SIGNAL(triggered()), em, SLOT(revertToSaved())); //Save Core::ActionManager::registerAction(&m_saveAction, Core::Constants::SAVE, qmlDesignerMainContext); connect(&m_saveAction, SIGNAL(triggered()), em, SLOT(saveDocument())); //Save As Core::ActionManager::registerAction(&m_saveAsAction, Core::Constants::SAVEAS, qmlDesignerMainContext); connect(&m_saveAsAction, SIGNAL(triggered()), em, SLOT(saveDocumentAs())); //Close Editor Core::ActionManager::registerAction(&m_closeCurrentEditorAction, Core::Constants::CLOSE, qmlDesignerMainContext); connect(&m_closeCurrentEditorAction, SIGNAL(triggered()), em, SLOT(closeEditor())); //Close All Core::ActionManager::registerAction(&m_closeAllEditorsAction, Core::Constants::CLOSEALL, qmlDesignerMainContext); connect(&m_closeAllEditorsAction, SIGNAL(triggered()), em, SLOT(closeAllEditors())); //Close All Others Action Core::ActionManager::registerAction(&m_closeOtherEditorsAction, Core::Constants::CLOSEOTHERS, qmlDesignerMainContext); connect(&m_closeOtherEditorsAction, SIGNAL(triggered()), em, SLOT(closeOtherEditors())); // Undo / Redo Core::ActionManager::registerAction(&m_undoAction, Core::Constants::UNDO, qmlDesignerMainContext); Core::ActionManager::registerAction(&m_redoAction, Core::Constants::REDO, qmlDesignerMainContext); Core::Command *command; //GoIntoComponent command = Core::ActionManager::registerAction(&m_goIntoComponentAction, Constants::GO_INTO_COMPONENT, qmlDesignerMainContext); command->setDefaultKeySequence(QKeySequence(Qt::Key_F2)); //Edit Menu command = Core::ActionManager::registerAction(&m_deleteAction, QmlDesigner::Constants::C_DELETE, qmlDesignerFormEditorContext); command = Core::ActionManager::registerAction(&m_deleteAction, QmlDesigner::Constants::C_DELETE, qmlDesignerNavigatorContext); command->setDefaultKeySequence(QKeySequence::Delete); command->setAttribute(Core::Command::CA_Hide); // don't show delete in other modes editMenu->addAction(command, Core::Constants::G_EDIT_COPYPASTE); command = Core::ActionManager::registerAction(&m_cutAction, Core::Constants::CUT, qmlDesignerFormEditorContext); command = Core::ActionManager::registerAction(&m_cutAction, Core::Constants::CUT, qmlDesignerNavigatorContext); command->setDefaultKeySequence(QKeySequence::Cut); editMenu->addAction(command, Core::Constants::G_EDIT_COPYPASTE); command = Core::ActionManager::registerAction(&m_copyAction, Core::Constants::COPY, qmlDesignerFormEditorContext); command = Core::ActionManager::registerAction(&m_copyAction, Core::Constants::COPY, qmlDesignerNavigatorContext); command->setDefaultKeySequence(QKeySequence::Copy); editMenu->addAction(command, Core::Constants::G_EDIT_COPYPASTE); command = Core::ActionManager::registerAction(&m_pasteAction, Core::Constants::PASTE, qmlDesignerFormEditorContext); command = Core::ActionManager::registerAction(&m_pasteAction, Core::Constants::PASTE, qmlDesignerNavigatorContext); command->setDefaultKeySequence(QKeySequence::Paste); editMenu->addAction(command, Core::Constants::G_EDIT_COPYPASTE); command = Core::ActionManager::registerAction(&m_selectAllAction, Core::Constants::SELECTALL, qmlDesignerFormEditorContext); command = Core::ActionManager::registerAction(&m_selectAllAction, Core::Constants::SELECTALL, qmlDesignerNavigatorContext); command->setDefaultKeySequence(QKeySequence::SelectAll); editMenu->addAction(command, Core::Constants::G_EDIT_SELECTALL); Core::ActionContainer *viewsMenu = Core::ActionManager::actionContainer(Core::Constants::M_WINDOW_VIEWS); command = Core::ActionManager::registerAction(&m_toggleLeftSidebarAction, Constants::TOGGLE_LEFT_SIDEBAR, qmlDesignerMainContext); command->setAttribute(Core::Command::CA_Hide); command->setDefaultKeySequence(QKeySequence("Ctrl+Alt+0")); viewsMenu->addAction(command); command = Core::ActionManager::registerAction(&m_toggleRightSidebarAction, Constants::TOGGLE_RIGHT_SIDEBAR, qmlDesignerMainContext); command->setAttribute(Core::Command::CA_Hide); command->setDefaultKeySequence(QKeySequence("Ctrl+Alt+Shift+0")); viewsMenu->addAction(command); command = Core::ActionManager::registerAction(&m_restoreDefaultViewAction, Constants::RESTORE_DEFAULT_VIEW, qmlDesignerMainContext); command->setAttribute(Core::Command::CA_Hide); viewsMenu->addAction(command); command = Core::ActionManager::registerAction(&m_hideSidebarsAction, Core::Constants::TOGGLE_SIDEBAR, qmlDesignerMainContext); if (Utils::HostOsInfo::isMacHost()) { // add second shortcut to trigger delete QAction *deleteAction = new QAction(this); deleteAction->setShortcut(QKeySequence(QLatin1String("Backspace"))); connect(deleteAction, SIGNAL(triggered()), &m_deleteAction, SIGNAL(triggered())); } } void ShortCutManager::updateActions(Core::IEditor* currentEditor) { int openedCount = Core::EditorManager::documentModel()->documentCount(); m_saveAction.setEnabled(currentEditor != 0 && currentEditor->document()->isModified()); m_saveAsAction.setEnabled(currentEditor != 0 && currentEditor->document()->isSaveAsAllowed()); m_revertToSavedAction.setEnabled(currentEditor != 0 && !currentEditor->document()->filePath().isEmpty() && currentEditor->document()->isModified()); QString quotedName; if (currentEditor) quotedName = '"' + currentEditor->document()->displayName() + '"'; m_saveAsAction.setText(tr("Save %1 As...").arg(quotedName)); m_saveAction.setText(tr("&Save %1").arg(quotedName)); m_revertToSavedAction.setText(tr("Revert %1 to Saved").arg(quotedName)); m_closeCurrentEditorAction.setEnabled(currentEditor != 0); m_closeCurrentEditorAction.setText(tr("Close %1").arg(quotedName)); m_closeAllEditorsAction.setEnabled(openedCount > 0); m_closeOtherEditorsAction.setEnabled(openedCount > 1); m_closeOtherEditorsAction.setText((openedCount > 1 ? tr("Close All Except %1").arg(quotedName) : tr("Close Others"))); } void ShortCutManager::undo() { if (currentDesignDocument()) currentDesignDocument()->undo(); } void ShortCutManager::redo() { if (currentDesignDocument()) currentDesignDocument()->redo(); } void ShortCutManager::deleteSelected() { if (currentDesignDocument()) currentDesignDocument()->deleteSelected(); } void ShortCutManager::cutSelected() { if (currentDesignDocument()) currentDesignDocument()->cutSelected(); } void ShortCutManager::copySelected() { if (currentDesignDocument()) currentDesignDocument()->copySelected(); } void ShortCutManager::paste() { if (currentDesignDocument()) currentDesignDocument()->paste(); } void ShortCutManager::selectAll() { if (currentDesignDocument()) currentDesignDocument()->selectAll(); } void ShortCutManager::toggleSidebars() { QmlDesignerPlugin::instance()->mainWidget()->toggleSidebars(); } void ShortCutManager::toggleLeftSidebar() { QmlDesignerPlugin::instance()->mainWidget()->toggleLeftSidebar(); } void ShortCutManager::toggleRightSidebar() { QmlDesignerPlugin::instance()->mainWidget()->toggleRightSidebar(); } void ShortCutManager::connectUndoActions(DesignDocument *designDocument) { if (designDocument) { connect(designDocument, SIGNAL(undoAvailable(bool)), this, SLOT(undoAvailable(bool))); connect(designDocument, SIGNAL(redoAvailable(bool)), this, SLOT(redoAvailable(bool))); } } void ShortCutManager::disconnectUndoActions(DesignDocument *designDocument) { if (currentDesignDocument()) { disconnect(designDocument, SIGNAL(undoAvailable(bool)), this, SLOT(undoAvailable(bool))); disconnect(designDocument, SIGNAL(redoAvailable(bool)), this, SLOT(redoAvailable(bool))); } } void ShortCutManager::updateUndoActions(DesignDocument *designDocument) { if (designDocument) { m_undoAction.setEnabled(designDocument->isUndoAvailable()); m_redoAction.setEnabled(designDocument->isRedoAvailable()); } else { m_undoAction.setEnabled(false); m_redoAction.setEnabled(false); } } DesignDocument *ShortCutManager::currentDesignDocument() const { return QmlDesignerPlugin::instance()->currentDesignDocument(); } void ShortCutManager::undoAvailable(bool isAvailable) { DesignDocument *documentController = qobject_cast<DesignDocument*>(sender()); if (currentDesignDocument() && currentDesignDocument() == documentController) { m_undoAction.setEnabled(isAvailable); } } void ShortCutManager::redoAvailable(bool isAvailable) { DesignDocument *documentController = qobject_cast<DesignDocument*>(sender()); if (currentDesignDocument() && currentDesignDocument() == documentController) { m_redoAction.setEnabled(isAvailable); } } void ShortCutManager::goIntoComponent() { if (currentDesignDocument() && currentDesignDocument()->currentModel() && currentDesignDocument()->rewriterView() && currentDesignDocument()->rewriterView()->hasSingleSelectedModelNode()) { DocumentManager::goIntoComponent(currentDesignDocument()->rewriterView()->singleSelectedModelNode()); } } } // namespace QmlDesigner <|endoftext|>
<commit_before>// // Created by Manuel Polzhofer on 19.05.15. // #include "TweeZCodeCompilerPipeline.h" #include <TweeParser.h> #include <fstream> #include <iostream> #include <memory> #include <map> #include <TweeFile.h> #include "AssemblyParser.h" #include "ZCodeObjects/ZCodeContainer.h" #include "ZCodeObjects/ZCodeMemorySpace.h" #include "ZCodeObjects/ZCodePkgAdrrPadding.h" #include <sstream> #include <plog/Log.h> #include <cstdint> using namespace std; void TweeZCodeCompilerPipeline::compile(string inputFileName, string outputFileName, ITweeCompiler &tweeCompiler, bool isTwee, bool outputAssembly) { log("Simple Compiler Pipeline started"); stringstream buffer; if(isTwee) { //source file is twee file ifstream inputFile(inputFileName); if(!inputFile) { LOG_ERROR << "Invalid input file specified: " << inputFileName; throw; // TODO: throw proper exception } Twee::TweeParser parser(&inputFile); std::unique_ptr<TweeFile> tweeFile; try { tweeFile = parser.parse(); } catch (const Twee::ParseException &e) { log("Parse error"); throw e; } log("Parsed twee file"); tweeCompiler.compile(*tweeFile, buffer); if(outputAssembly) { ofstream file(outputFileName, ios::out); file << buffer.rdbuf(); return; } } else { //source file is assembly file std::ifstream in(inputFileName); buffer << in.rdbuf(); } buffer << Utils::getMallocLib(); shared_ptr<ZCodeContainer> zcode = shared_ptr<ZCodeContainer>(new ZCodeContainer("ZCode Container")); //create header shared_ptr<ZCodeHeader> header = shared_ptr<ZCodeHeader>(new ZCodeHeader()); zcode->add(header); //create dynamicMemory shared_ptr<ZCodeContainer> dynamicMemory = shared_ptr<ZCodeContainer>(new ZCodeContainer("dynamic memory")); Utils::dynamicMemory = dynamicMemory; shared_ptr<ZCodeObject> globalVariablesTable = shared_ptr<ZCodeObject>(new ZCodeMemorySpace((0xff - 0x0f)*2+1000,"global variables table"));// Global Var Table dynamicMemory->add(shared_ptr<ZCodeObject>(new ZCodePkgAdrrPadding())); dynamicMemory->add(globalVariablesTable); shared_ptr<ZCodeObject> globalObjectsTable = shared_ptr<ZCodeObject>(new ZCodeMemorySpace((0x2f0-0x140), "global objects")); dynamicMemory->add(shared_ptr<ZCodeObject>(new ZCodePkgAdrrPadding())); dynamicMemory->add(globalObjectsTable); zcode->add(dynamicMemory); //create staticMemory shared_ptr<ZCodeContainer> staticMemory = shared_ptr<ZCodeContainer>(new ZCodeContainer("static memory")); shared_ptr<ZCodeObject> padding = shared_ptr<ZCodeObject>(new ZCodePkgAdrrPadding()); staticMemory->add(padding); zcode->add(staticMemory); //create hight Memory shared_ptr<ZCodeContainer> highMemory = shared_ptr<ZCodeContainer>(new ZCodeContainer("high memory")); zcode->add(highMemory); //parse AssemblyParser parser = AssemblyParser(); parser.readAssembly(buffer,dynamicMemory,staticMemory,highMemory); //init header header->setRoutinesOffset(88); header->setStaticStringsOffset(99); header->setFileLength(3, 52); header->locOfGlobVarTable = globalVariablesTable->getOffset(); header->baseOfStatMem = (uint16_t) (staticMemory->getOffset()); header->baseOfHighMem = (uint16_t) (highMemory->getOffset()); header->initValOfPC = header->baseOfHighMem; header->locOfObjTable = globalObjectsTable->offset; //concat memory sections vector<bitset<8>> zCode; zcode->print(zCode); zcode->printMemory(); //calculate fileSize size_t fileSize = Utils::calculateNextPackageAddress(zCode.size()); zCode = addFileSizeToHeader(zCode, fileSize); //generate empty space for padding size_t empty = fileSize - zCode.size(); Utils::fillWithBytes(zCode, 0, (empty > 0) ? empty : 0); BinaryFileWriter binaryFileWriter; binaryFileWriter.write(outputFileName, zCode); log("ZCode File '" + outputFileName + "' generated"); zcode->cleanup(); Utils::dynamicMemory = NULL; } std::vector<std::bitset<8>> TweeZCodeCompilerPipeline::addFileSizeToHeader(std::vector<std::bitset<8>> zCode, size_t fileSize) { //change fileSize in header bitset<16> shortVal(fileSize / 8); bitset<8> firstHalf, secondHalf; for (size_t i = 0; i < 8; i++) { secondHalf.set(i, shortVal[i]); } for (size_t i = 8; i < 16; i++) { firstHalf.set(i - 8, shortVal[i]); } zCode[ZCodeHeader::HEADER_FILE_SIZE_POSITION] = firstHalf; zCode[ZCodeHeader::HEADER_FILE_SIZE_POSITION + 1] = secondHalf; return zCode; } void TweeZCodeCompilerPipeline::printHex(std::vector<std::bitset<8>> bitsetList) { for (unsigned int i = 0; i < bitsetList.size(); i++) { bitset<8> set(bitsetList.at(i)); LOG_DEBUG << hex << set.to_ulong(); } LOG_DEBUG; } std::vector<std::bitset<8>> TweeZCodeCompilerPipeline::printGlobalTable(int offset) { vector<bitset<8>> akk = vector<bitset<8>>(); for (int i = 0; i < (0xff - 0x10); i++) { int adr = offset + (0xff - 0x10) * 2 + i * 100; bitset<8> one = bitset<8>((unsigned long long int) adr / 255); bitset<8> two = bitset<8>((unsigned long long int) adr % 256); akk.push_back(one); akk.push_back(two); } for (int i = 0; i < (0xff - 0x10); i++) { akk.push_back(bitset<8>(4)); akk.push_back(bitset<8>(0)); Utils::fillWithBytes(akk, 0, 96); akk.push_back(bitset<8>(0x80)); akk.push_back(bitset<8>(0)); } return akk; } void TweeZCodeCompilerPipeline::log(string message) { LOG_DEBUG << "Compiler: " << message << " . . ." << "\n"; } <commit_msg>add newline between malloc library to avoid assembly errors<commit_after>// // Created by Manuel Polzhofer on 19.05.15. // #include "TweeZCodeCompilerPipeline.h" #include <TweeParser.h> #include <fstream> #include <iostream> #include <memory> #include <map> #include <TweeFile.h> #include "AssemblyParser.h" #include "ZCodeObjects/ZCodeContainer.h" #include "ZCodeObjects/ZCodeMemorySpace.h" #include "ZCodeObjects/ZCodePkgAdrrPadding.h" #include <sstream> #include <plog/Log.h> #include <cstdint> using namespace std; void TweeZCodeCompilerPipeline::compile(string inputFileName, string outputFileName, ITweeCompiler &tweeCompiler, bool isTwee, bool outputAssembly) { log("Simple Compiler Pipeline started"); stringstream buffer; if(isTwee) { //source file is twee file ifstream inputFile(inputFileName); if(!inputFile) { LOG_ERROR << "Invalid input file specified: " << inputFileName; throw; // TODO: throw proper exception } Twee::TweeParser parser(&inputFile); std::unique_ptr<TweeFile> tweeFile; try { tweeFile = parser.parse(); } catch (const Twee::ParseException &e) { log("Parse error"); throw e; } log("Parsed twee file"); tweeCompiler.compile(*tweeFile, buffer); if(outputAssembly) { ofstream file(outputFileName, ios::out); file << buffer.rdbuf(); return; } } else { //source file is assembly file std::ifstream in(inputFileName); buffer << in.rdbuf(); } buffer << endl << Utils::getMallocLib(); shared_ptr<ZCodeContainer> zcode = shared_ptr<ZCodeContainer>(new ZCodeContainer("ZCode Container")); //create header shared_ptr<ZCodeHeader> header = shared_ptr<ZCodeHeader>(new ZCodeHeader()); zcode->add(header); //create dynamicMemory shared_ptr<ZCodeContainer> dynamicMemory = shared_ptr<ZCodeContainer>(new ZCodeContainer("dynamic memory")); Utils::dynamicMemory = dynamicMemory; shared_ptr<ZCodeObject> globalVariablesTable = shared_ptr<ZCodeObject>(new ZCodeMemorySpace((0xff - 0x0f)*2+1000,"global variables table"));// Global Var Table dynamicMemory->add(shared_ptr<ZCodeObject>(new ZCodePkgAdrrPadding())); dynamicMemory->add(globalVariablesTable); shared_ptr<ZCodeObject> globalObjectsTable = shared_ptr<ZCodeObject>(new ZCodeMemorySpace((0x2f0-0x140), "global objects")); dynamicMemory->add(shared_ptr<ZCodeObject>(new ZCodePkgAdrrPadding())); dynamicMemory->add(globalObjectsTable); zcode->add(dynamicMemory); //create staticMemory shared_ptr<ZCodeContainer> staticMemory = shared_ptr<ZCodeContainer>(new ZCodeContainer("static memory")); shared_ptr<ZCodeObject> padding = shared_ptr<ZCodeObject>(new ZCodePkgAdrrPadding()); staticMemory->add(padding); zcode->add(staticMemory); //create hight Memory shared_ptr<ZCodeContainer> highMemory = shared_ptr<ZCodeContainer>(new ZCodeContainer("high memory")); zcode->add(highMemory); //parse AssemblyParser parser = AssemblyParser(); parser.readAssembly(buffer,dynamicMemory,staticMemory,highMemory); //init header header->setRoutinesOffset(88); header->setStaticStringsOffset(99); header->setFileLength(3, 52); header->locOfGlobVarTable = globalVariablesTable->getOffset(); header->baseOfStatMem = (uint16_t) (staticMemory->getOffset()); header->baseOfHighMem = (uint16_t) (highMemory->getOffset()); header->initValOfPC = header->baseOfHighMem; header->locOfObjTable = globalObjectsTable->offset; //concat memory sections vector<bitset<8>> zCode; zcode->print(zCode); zcode->printMemory(); //calculate fileSize size_t fileSize = Utils::calculateNextPackageAddress(zCode.size()); zCode = addFileSizeToHeader(zCode, fileSize); //generate empty space for padding size_t empty = fileSize - zCode.size(); Utils::fillWithBytes(zCode, 0, (empty > 0) ? empty : 0); BinaryFileWriter binaryFileWriter; binaryFileWriter.write(outputFileName, zCode); log("ZCode File '" + outputFileName + "' generated"); zcode->cleanup(); Utils::dynamicMemory = NULL; } std::vector<std::bitset<8>> TweeZCodeCompilerPipeline::addFileSizeToHeader(std::vector<std::bitset<8>> zCode, size_t fileSize) { //change fileSize in header bitset<16> shortVal(fileSize / 8); bitset<8> firstHalf, secondHalf; for (size_t i = 0; i < 8; i++) { secondHalf.set(i, shortVal[i]); } for (size_t i = 8; i < 16; i++) { firstHalf.set(i - 8, shortVal[i]); } zCode[ZCodeHeader::HEADER_FILE_SIZE_POSITION] = firstHalf; zCode[ZCodeHeader::HEADER_FILE_SIZE_POSITION + 1] = secondHalf; return zCode; } void TweeZCodeCompilerPipeline::printHex(std::vector<std::bitset<8>> bitsetList) { for (unsigned int i = 0; i < bitsetList.size(); i++) { bitset<8> set(bitsetList.at(i)); LOG_DEBUG << hex << set.to_ulong(); } LOG_DEBUG; } std::vector<std::bitset<8>> TweeZCodeCompilerPipeline::printGlobalTable(int offset) { vector<bitset<8>> akk = vector<bitset<8>>(); for (int i = 0; i < (0xff - 0x10); i++) { int adr = offset + (0xff - 0x10) * 2 + i * 100; bitset<8> one = bitset<8>((unsigned long long int) adr / 255); bitset<8> two = bitset<8>((unsigned long long int) adr % 256); akk.push_back(one); akk.push_back(two); } for (int i = 0; i < (0xff - 0x10); i++) { akk.push_back(bitset<8>(4)); akk.push_back(bitset<8>(0)); Utils::fillWithBytes(akk, 0, 96); akk.push_back(bitset<8>(0x80)); akk.push_back(bitset<8>(0)); } return akk; } void TweeZCodeCompilerPipeline::log(string message) { LOG_DEBUG << "Compiler: " << message << " . . ." << "\n"; } <|endoftext|>
<commit_before>#include <iostream> #ifdef WITH_THREADS #include <boost/thread/thread.hpp> #endif #include "moses/TypeDef.h" #include "moses/TranslationModel/CompactPT/PhraseTableCreator.h" #include "util/file.hh" using namespace Moses; void printHelp(char **argv) { std::cerr << "Usage " << argv[0] << ":\n" " options: \n" "\t-in string -- input table file name\n" "\t-out string -- prefix of binary table file\n" "\t-T string -- path to temporary directory (uses /tmp by default)\n" "\t-nscores int -- number of score components in phrase table\n" "\t-no-alignment-info -- do not include alignment info in the binary phrase table\n" #ifdef WITH_THREADS "\t-threads int|all -- number of threads used for conversion\n" #endif "\n advanced:\n" "\t-encoding string -- encoding type: PREnc REnc None (default PREnc)\n" "\t-rankscore int -- score index of P(t|s) (default 2)\n" "\t-maxrank int -- maximum rank for PREnc (default 100)\n" "\t-landmark int -- use landmark phrase every 2^n source phrases (default 10)\n" "\t-fingerprint int -- number of bits used for source phrase fingerprints (default 16)\n" "\t-join-scores -- single set of Huffman codes for score components\n" "\t-quantize int -- maximum number of scores per score component\n" "\t-no-warnings -- suppress warnings about missing alignment data\n" "\n" " For more information see: http://www.statmt.org/moses/?n=Moses.AdvancedFeatures#ntoc6\n\n" " If you use this please cite:\n\n" " @article { junczys_pbml98_2012,\n" " author = { Marcin Junczys-Dowmunt },\n" " title = { Phrasal Rank-Encoding: Exploiting Phrase Redundancy and\n" " Translational Relations for Phrase Table Compression },\n" " journal = { The Prague Bulletin of Mathematical Linguistics },\n" " volume = { 98 },\n" " year = { 2012 },\n" " note = { Proceedings of the MT Marathon 2012, Edinburgh },\n" " }\n\n" " Acknowledgments: Part of this research was carried out at and funded by\n" " the World Intellectual Property Organization (WIPO) in Geneva.\n\n"; } int main(int argc, char **argv) { std::string inFilePath; std::string outFilePath("out"); std::string tempfilePath; PhraseTableCreator::Coding coding = PhraseTableCreator::PREnc; size_t numScoreComponent = 5; size_t orderBits = 10; size_t fingerprintBits = 16; bool useAlignmentInfo = true; bool multipleScoreTrees = true; size_t quantize = 0; size_t maxRank = 100; bool sortScoreIndexSet = false; size_t sortScoreIndex = 2; bool warnMe = true; size_t threads = 1; if(1 >= argc) { printHelp(argv); return 1; } for(int i = 1; i < argc; ++i) { std::string arg(argv[i]); if("-in" == arg && i+1 < argc) { ++i; inFilePath = argv[i]; } else if("-out" == arg && i+1 < argc) { ++i; outFilePath = argv[i]; } else if("-T" == arg && i+1 < argc) { ++i; tempfilePath = argv[i]; util::NormalizeTempPrefix(tempfilePath); } else if("-encoding" == arg && i+1 < argc) { ++i; std::string val(argv[i]); if(val == "None" || val == "none") { coding = PhraseTableCreator::None; } else if(val == "REnc" || val == "renc") { coding = PhraseTableCreator::REnc; } else if(val == "PREnc" || val == "prenc") { coding = PhraseTableCreator::PREnc; } } else if("-maxrank" == arg && i+1 < argc) { ++i; maxRank = atoi(argv[i]); } else if("-nscores" == arg && i+1 < argc) { ++i; numScoreComponent = atoi(argv[i]); } else if("-rankscore" == arg && i+1 < argc) { ++i; sortScoreIndex = atoi(argv[i]); sortScoreIndexSet = true; } else if("-no-alignment-info" == arg) { useAlignmentInfo = false; } else if("-landmark" == arg && i+1 < argc) { ++i; orderBits = atoi(argv[i]); } else if("-fingerprint" == arg && i+1 < argc) { ++i; fingerprintBits = atoi(argv[i]); } else if("-join-scores" == arg) { multipleScoreTrees = false; } else if("-quantize" == arg && i+1 < argc) { ++i; quantize = atoi(argv[i]); } else if("-no-warnings" == arg) { warnMe = false; } else if("-threads" == arg && i+1 < argc) { #ifdef WITH_THREADS ++i; if(std::string(argv[i]) == "all") { threads = boost::thread::hardware_concurrency(); if(!threads) { std::cerr << "Could not determine number of hardware threads, setting to 1" << std::endl; threads = 1; } } else threads = atoi(argv[i]); #else std::cerr << "Thread support not compiled in" << std::endl; exit(1); #endif } else { //something's wrong... print help printHelp(argv); return 1; } } if(!sortScoreIndexSet && numScoreComponent != 5 && coding == PhraseTableCreator::PREnc) { std::cerr << "WARNING: You are using a nonstandard number of scores (" << numScoreComponent << ") with PREnc. Set the index of P(t|s) " "with -rankscore int if it is not " << sortScoreIndex << "." << std::endl; } if(sortScoreIndex >= numScoreComponent) { std::cerr << "ERROR: -rankscore " << sortScoreIndex << " is out of range (0 ... " << (numScoreComponent-1) << ")" << std::endl; abort(); } if(outFilePath.rfind(".minphr") != outFilePath.size() - 7) outFilePath += ".minphr"; PhraseTableCreator(inFilePath, outFilePath, tempfilePath, numScoreComponent, sortScoreIndex, coding, orderBits, fingerprintBits, useAlignmentInfo, multipleScoreTrees, quantize, maxRank, warnMe #ifdef WITH_THREADS , threads #endif ); } <commit_msg>Set default number of scores to 4<commit_after>#include <iostream> #ifdef WITH_THREADS #include <boost/thread/thread.hpp> #endif #include "moses/TypeDef.h" #include "moses/TranslationModel/CompactPT/PhraseTableCreator.h" #include "util/file.hh" using namespace Moses; void printHelp(char **argv) { std::cerr << "Usage " << argv[0] << ":\n" " options: \n" "\t-in string -- input table file name\n" "\t-out string -- prefix of binary table file\n" "\t-T string -- path to temporary directory (uses /tmp by default)\n" "\t-nscores int -- number of score components in phrase table\n" "\t-no-alignment-info -- do not include alignment info in the binary phrase table\n" #ifdef WITH_THREADS "\t-threads int|all -- number of threads used for conversion\n" #endif "\n advanced:\n" "\t-encoding string -- encoding type: PREnc REnc None (default PREnc)\n" "\t-rankscore int -- score index of P(t|s) (default 2)\n" "\t-maxrank int -- maximum rank for PREnc (default 100)\n" "\t-landmark int -- use landmark phrase every 2^n source phrases (default 10)\n" "\t-fingerprint int -- number of bits used for source phrase fingerprints (default 16)\n" "\t-join-scores -- single set of Huffman codes for score components\n" "\t-quantize int -- maximum number of scores per score component\n" "\t-no-warnings -- suppress warnings about missing alignment data\n" "\n" " For more information see: http://www.statmt.org/moses/?n=Moses.AdvancedFeatures#ntoc6\n\n" " If you use this please cite:\n\n" " @article { junczys_pbml98_2012,\n" " author = { Marcin Junczys-Dowmunt },\n" " title = { Phrasal Rank-Encoding: Exploiting Phrase Redundancy and\n" " Translational Relations for Phrase Table Compression },\n" " journal = { The Prague Bulletin of Mathematical Linguistics },\n" " volume = { 98 },\n" " year = { 2012 },\n" " note = { Proceedings of the MT Marathon 2012, Edinburgh },\n" " }\n\n" " Acknowledgments: Part of this research was carried out at and funded by\n" " the World Intellectual Property Organization (WIPO) in Geneva.\n\n"; } int main(int argc, char **argv) { std::string inFilePath; std::string outFilePath("out"); std::string tempfilePath; PhraseTableCreator::Coding coding = PhraseTableCreator::PREnc; size_t numScoreComponent = 4; size_t orderBits = 10; size_t fingerprintBits = 16; bool useAlignmentInfo = true; bool multipleScoreTrees = true; size_t quantize = 0; size_t maxRank = 100; bool sortScoreIndexSet = false; size_t sortScoreIndex = 2; bool warnMe = true; size_t threads = 1; if(1 >= argc) { printHelp(argv); return 1; } for(int i = 1; i < argc; ++i) { std::string arg(argv[i]); if("-in" == arg && i+1 < argc) { ++i; inFilePath = argv[i]; } else if("-out" == arg && i+1 < argc) { ++i; outFilePath = argv[i]; } else if("-T" == arg && i+1 < argc) { ++i; tempfilePath = argv[i]; util::NormalizeTempPrefix(tempfilePath); } else if("-encoding" == arg && i+1 < argc) { ++i; std::string val(argv[i]); if(val == "None" || val == "none") { coding = PhraseTableCreator::None; } else if(val == "REnc" || val == "renc") { coding = PhraseTableCreator::REnc; } else if(val == "PREnc" || val == "prenc") { coding = PhraseTableCreator::PREnc; } } else if("-maxrank" == arg && i+1 < argc) { ++i; maxRank = atoi(argv[i]); } else if("-nscores" == arg && i+1 < argc) { ++i; numScoreComponent = atoi(argv[i]); } else if("-rankscore" == arg && i+1 < argc) { ++i; sortScoreIndex = atoi(argv[i]); sortScoreIndexSet = true; } else if("-no-alignment-info" == arg) { useAlignmentInfo = false; } else if("-landmark" == arg && i+1 < argc) { ++i; orderBits = atoi(argv[i]); } else if("-fingerprint" == arg && i+1 < argc) { ++i; fingerprintBits = atoi(argv[i]); } else if("-join-scores" == arg) { multipleScoreTrees = false; } else if("-quantize" == arg && i+1 < argc) { ++i; quantize = atoi(argv[i]); } else if("-no-warnings" == arg) { warnMe = false; } else if("-threads" == arg && i+1 < argc) { #ifdef WITH_THREADS ++i; if(std::string(argv[i]) == "all") { threads = boost::thread::hardware_concurrency(); if(!threads) { std::cerr << "Could not determine number of hardware threads, setting to 1" << std::endl; threads = 1; } } else threads = atoi(argv[i]); #else std::cerr << "Thread support not compiled in" << std::endl; exit(1); #endif } else { //something's wrong... print help printHelp(argv); return 1; } } if(!sortScoreIndexSet && numScoreComponent != 4 && coding == PhraseTableCreator::PREnc) { std::cerr << "WARNING: You are using a nonstandard number of scores (" << numScoreComponent << ") with PREnc. Set the index of P(t|s) " "with -rankscore int if it is not " << sortScoreIndex << "." << std::endl; } if(sortScoreIndex >= numScoreComponent) { std::cerr << "ERROR: -rankscore " << sortScoreIndex << " is out of range (0 ... " << (numScoreComponent-1) << ")" << std::endl; abort(); } if(outFilePath.rfind(".minphr") != outFilePath.size() - 7) outFilePath += ".minphr"; PhraseTableCreator(inFilePath, outFilePath, tempfilePath, numScoreComponent, sortScoreIndex, coding, orderBits, fingerprintBits, useAlignmentInfo, multipleScoreTrees, quantize, maxRank, warnMe #ifdef WITH_THREADS , threads #endif ); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkRotationalExtrusionFilter.cc Language: C++ Date: 09 Oct 1995 Version: 1.13 Copyright (c) 1993-1996 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 "vtkRotationalExtrusionFilter.h" #include "vtkMath.h" #include "vtkIdList.h" // Description: // Create object with capping on, angle of 360 degrees, resolution = 12, and // no translation along z-axis. // vector (0,0,1), and point (0,0,0). vtkRotationalExtrusionFilter::vtkRotationalExtrusionFilter() { this->Capping = 1; this->Angle = 360.0; this->DeltaRadius = 0.0; this->Translation = 0.0; this->Resolution = 12; // 30 degree increments } void vtkRotationalExtrusionFilter::Execute() { int numPts, numCells; vtkPolyData *input=(vtkPolyData *)this->Input; vtkPointData *pd=input->GetPointData(); vtkPolyData mesh; vtkPoints *inPts; vtkCellArray *inVerts, *inLines, *inPolys, *inStrips; int npts, *pts, numEdges, cellId, dim; int ptId, ncells; float *x, newX[3], radius, angleIncr, radIncr, transIncr; float psi, theta; vtkFloatPoints *newPts; vtkCellArray *newLines=NULL, *newPolys=NULL, *newStrips=NULL; vtkCell *cell, *edge; vtkIdList cellIds(VTK_CELL_SIZE), *cellPts; int i, j, k, p1, p2; vtkPolyData *output=(vtkPolyData *)this->Output; vtkPointData *outPD=output->GetPointData(); // // Initialize / check input // vtkDebugMacro(<<"Rotationally extruding data"); numPts = input->GetNumberOfPoints(); numCells = input->GetNumberOfCells(); if (numPts < 1 || numCells < 1) { vtkErrorMacro(<<"No data to extrude!"); return; } // // Build cell data structure. // inPts = input->GetPoints(); inVerts = input->GetVerts(); inLines = input->GetLines(); inPolys = input->GetPolys(); inStrips = input->GetStrips(); mesh.SetPoints(inPts); mesh.SetVerts(inVerts); mesh.SetLines(inLines); mesh.SetPolys(inPolys); mesh.SetStrips(inStrips); if ( inPolys || inStrips ) mesh.BuildLinks(); // // Allocate memory for output. We don't copy normals because surface geometry // is modified. // outPD->CopyNormalsOff(); outPD->CopyAllocate(pd,(this->Resolution+1)*numPts); newPts = new vtkFloatPoints((this->Resolution+1)*numPts); if ( (ncells=inVerts->GetNumberOfCells()) > 0 ) { newLines = vtkCellArray::New(); newLines->Allocate(newLines->EstimateSize(ncells,this->Resolution+1)); } // arbitrary initial allocation size ncells = inLines->GetNumberOfCells() + inPolys->GetNumberOfCells()/10 + inStrips->GetNumberOfCells()/10; ncells = (ncells < 100 ? 100 : ncells); newStrips = vtkCellArray::New(); newStrips->Allocate(newStrips->EstimateSize(ncells,2*(this->Resolution+1))); // copy points for (ptId=0; ptId < numPts; ptId++) //base level { newPts->InsertPoint(ptId,inPts->GetPoint(ptId)); outPD->CopyData(pd,ptId,ptId); } // loop assumes rotation around z-axis radIncr = this->DeltaRadius / this->Resolution; transIncr = this->Translation / this->Resolution; angleIncr = this->Angle / this->Resolution * vtkMath::DegreesToRadians(); for ( i = 1; i <= this->Resolution; i++ ) { for (ptId=0; ptId < numPts; ptId++) { x = inPts->GetPoint(ptId); //convert to cylindrical radius = sqrt(x[0]*x[0] + x[1]*x[1]); theta = acos((double)x[0]/radius); if ( (psi=asin((double)x[1]/radius)) < 0.0 ) { if ( theta < (vtkMath::Pi()/2.0) ) theta = 2.0*vtkMath::Pi() + psi; else theta = vtkMath::Pi() - psi; } //increment angle radius += i*radIncr; newX[0] = radius * cos (i*angleIncr + theta); newX[1] = radius * sin (i*angleIncr + theta); newX[2] = x[2] + i * transIncr; newPts->InsertPoint(ptId+i*numPts,newX); outPD->CopyData(pd,ptId,ptId+i*numPts); } } // // If capping is on, copy 2D cells to output (plus create cap) // if ( this->Capping && (this->Angle != 360.0 || this->DeltaRadius != 0.0 || this->Translation != 0.0) ) { if ( inPolys->GetNumberOfCells() > 0 ) { newPolys = new vtkCellArray(inPolys->GetSize()); for ( inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); ) { newPolys->InsertNextCell(npts,pts); newPolys->InsertNextCell(npts); // note that we need to reverse the vertex order on the far cap for (i=0; i < npts; i++) newPolys->InsertCellPoint(pts[i] + this->Resolution*numPts); } } if ( inStrips->GetNumberOfCells() > 0 ) { for ( inStrips->InitTraversal(); inStrips->GetNextCell(npts,pts); ) { newStrips->InsertNextCell(npts,pts); newStrips->InsertNextCell(npts); for (i=0; i < npts; i++) newStrips->InsertCellPoint(pts[i] + this->Resolution*numPts); } } } // // Loop over all polygons and triangle strips searching for boundary edges. // If boundary edge found, extrude triangle strip. // for ( cellId=0; cellId < numCells; cellId++) { cell = mesh.GetCell(cellId); cellPts = cell->GetPointIds(); if ( (dim=cell->GetCellDimension()) == 0 ) //create lines from points { for (i=0; i<cellPts->GetNumberOfIds(); i++) { ptId = cellPts->GetId(i); newLines->InsertNextCell(this->Resolution+1); for ( j=0; j<=this->Resolution; j++ ) newLines->InsertCellPoint(ptId + j*numPts); } } else if ( dim == 1 ) // create strips from lines { for (i=0; i < (cellPts->GetNumberOfIds()-1); i++) { p1 = cellPts->GetId(i); p2 = cellPts->GetId(i+1); newStrips->InsertNextCell(2*(this->Resolution+1)); for ( j=0; j<=this->Resolution; j++) { newStrips->InsertCellPoint(p2 + j*numPts); newStrips->InsertCellPoint(p1 + j*numPts); } } } else if ( dim == 2 ) // create strips from boundary edges { numEdges = cell->GetNumberOfEdges(); for (i=0; i<numEdges; i++) { edge = cell->GetEdge(i); for (j=0; j<(edge->GetNumberOfPoints()-1); j++) { p1 = edge->PointIds.GetId(j); p2 = edge->PointIds.GetId(j+1); mesh.GetCellEdgeNeighbors(cellId, p1, p2, cellIds); if ( cellIds.GetNumberOfIds() < 1 ) //generate strip { newStrips->InsertNextCell(2*(this->Resolution+1)); for (k=0; k<=this->Resolution; k++) { newStrips->InsertCellPoint(p2 + k*numPts); newStrips->InsertCellPoint(p1 + k*numPts); } } //if boundary edge } //for each sub-edge } //for each edge } //for each polygon or triangle strip } //for each cell // // Update ourselves and release memory // output->SetPoints(newPts); newPts->Delete(); if ( newLines ) { output->SetLines(newLines); newLines->Delete(); } if ( newPolys ) { output->SetPolys(newPolys); newPolys->Delete(); } output->SetStrips(newStrips); newStrips->Delete(); output->Squeeze(); } void vtkRotationalExtrusionFilter::PrintSelf(ostream& os, vtkIndent indent) { vtkPolyToPolyFilter::PrintSelf(os,indent); os << indent << "Resolution: " << this->Resolution << "\n"; os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n"); os << indent << "Angle: " << this->Angle << "\n"; os << indent << "Translation: " << this->Translation << "\n"; os << indent << "Delta Radius: " << this->DeltaRadius << "\n"; } <commit_msg>some bug fixes -ken<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkRotationalExtrusionFilter.cc Language: C++ Date: 09 Oct 1995 Version: 1.13 Copyright (c) 1993-1996 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 "vtkRotationalExtrusionFilter.h" #include "vtkMath.h" #include "vtkIdList.h" // Description: // Create object with capping on, angle of 360 degrees, resolution = 12, and // no translation along z-axis. // vector (0,0,1), and point (0,0,0). vtkRotationalExtrusionFilter::vtkRotationalExtrusionFilter() { this->Capping = 1; this->Angle = 360.0; this->DeltaRadius = 0.0; this->Translation = 0.0; this->Resolution = 12; // 30 degree increments } void vtkRotationalExtrusionFilter::Execute() { int numPts, numCells; vtkPolyData *input= this->GetInput(); vtkPointData *pd=input->GetPointData(); vtkPolyData mesh; vtkPoints *inPts; vtkCellArray *inVerts, *inLines, *inPolys, *inStrips; int npts, *pts, numEdges, cellId, dim; int ptId, ncells; float *x, newX[3], radius, angleIncr, radIncr, transIncr; float psi, theta; vtkFloatPoints *newPts; vtkCellArray *newLines=NULL, *newPolys=NULL, *newStrips=NULL; vtkCell *cell, *edge; vtkIdList cellIds(VTK_CELL_SIZE), *cellPts; int i, j, k, p1, p2; vtkPolyData *output= this->GetOutput(); vtkPointData *outPD=output->GetPointData(); double tempd; // // Initialize / check input // vtkDebugMacro(<<"Rotationally extruding data"); numPts = input->GetNumberOfPoints(); numCells = input->GetNumberOfCells(); if (numPts < 1 || numCells < 1) { vtkErrorMacro(<<"No data to extrude!"); return; } // // Build cell data structure. // inPts = input->GetPoints(); inVerts = input->GetVerts(); inLines = input->GetLines(); inPolys = input->GetPolys(); inStrips = input->GetStrips(); mesh.SetPoints(inPts); mesh.SetVerts(inVerts); mesh.SetLines(inLines); mesh.SetPolys(inPolys); mesh.SetStrips(inStrips); if ( inPolys || inStrips ) mesh.BuildLinks(); // // Allocate memory for output. We don't copy normals because surface geometry // is modified. // outPD->CopyNormalsOff(); outPD->CopyAllocate(pd,(this->Resolution+1)*numPts); newPts = new vtkFloatPoints((this->Resolution+1)*numPts); if ( (ncells=inVerts->GetNumberOfCells()) > 0 ) { newLines = vtkCellArray::New(); newLines->Allocate(newLines->EstimateSize(ncells,this->Resolution+1)); } // arbitrary initial allocation size ncells = inLines->GetNumberOfCells() + inPolys->GetNumberOfCells()/10 + inStrips->GetNumberOfCells()/10; ncells = (ncells < 100 ? 100 : ncells); newStrips = vtkCellArray::New(); newStrips->Allocate(newStrips->EstimateSize(ncells,2*(this->Resolution+1))); // copy points for (ptId=0; ptId < numPts; ptId++) //base level { newPts->InsertPoint(ptId,inPts->GetPoint(ptId)); outPD->CopyData(pd,ptId,ptId); } // loop assumes rotation around z-axis radIncr = this->DeltaRadius / this->Resolution; transIncr = this->Translation / this->Resolution; angleIncr = this->Angle / this->Resolution * vtkMath::DegreesToRadians(); for ( i = 1; i <= this->Resolution; i++ ) { for (ptId=0; ptId < numPts; ptId++) { x = inPts->GetPoint(ptId); //convert to cylindrical radius = sqrt(x[0]*x[0] + x[1]*x[1]); if (radius > 0.0) { tempd = (double)x[0]/radius; if (tempd < -1.0) tempd = -1.0; if (tempd > 1.0) tempd = 1.0; theta = acos(tempd); tempd = (double)x[1]/radius; if (tempd < -1.0) tempd = -1.0; if (tempd > 1.0) tempd = 1.0; if ( (psi=asin(tempd)) < 0.0 ) { if ( theta < (vtkMath::Pi()/2.0) ) theta = 2.0*vtkMath::Pi() + psi; else theta = vtkMath::Pi() - psi; } //increment angle radius += i*radIncr; newX[0] = radius * cos (i*angleIncr + theta); newX[1] = radius * sin (i*angleIncr + theta); newX[2] = x[2] + i * transIncr; } else // radius is zero { newX[0] = 0.0; newX[1] = 0.0; newX[2] = x[2] + i * transIncr; } newPts->InsertPoint(ptId+i*numPts,newX); outPD->CopyData(pd,ptId,ptId+i*numPts); } } // // If capping is on, copy 2D cells to output (plus create cap) // if ( this->Capping && (this->Angle != 360.0 || this->DeltaRadius != 0.0 || this->Translation != 0.0) ) { if ( inPolys->GetNumberOfCells() > 0 ) { newPolys = new vtkCellArray(inPolys->GetSize()); for ( inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); ) { newPolys->InsertNextCell(npts,pts); newPolys->InsertNextCell(npts); // note that we need to reverse the vertex order on the far cap for (i=0; i < npts; i++) newPolys->InsertCellPoint(pts[i] + this->Resolution*numPts); } } if ( inStrips->GetNumberOfCells() > 0 ) { for ( inStrips->InitTraversal(); inStrips->GetNextCell(npts,pts); ) { newStrips->InsertNextCell(npts,pts); newStrips->InsertNextCell(npts); for (i=0; i < npts; i++) newStrips->InsertCellPoint(pts[i] + this->Resolution*numPts); } } } // // Loop over all polygons and triangle strips searching for boundary edges. // If boundary edge found, extrude triangle strip. // for ( cellId=0; cellId < numCells; cellId++) { cell = mesh.GetCell(cellId); cellPts = cell->GetPointIds(); if ( (dim=cell->GetCellDimension()) == 0 ) //create lines from points { for (i=0; i<cellPts->GetNumberOfIds(); i++) { ptId = cellPts->GetId(i); newLines->InsertNextCell(this->Resolution+1); for ( j=0; j<=this->Resolution; j++ ) newLines->InsertCellPoint(ptId + j*numPts); } } else if ( dim == 1 ) // create strips from lines { for (i=0; i < (cellPts->GetNumberOfIds()-1); i++) { p1 = cellPts->GetId(i); p2 = cellPts->GetId(i+1); newStrips->InsertNextCell(2*(this->Resolution+1)); for ( j=0; j<=this->Resolution; j++) { newStrips->InsertCellPoint(p2 + j*numPts); newStrips->InsertCellPoint(p1 + j*numPts); } } } else if ( dim == 2 ) // create strips from boundary edges { numEdges = cell->GetNumberOfEdges(); for (i=0; i<numEdges; i++) { edge = cell->GetEdge(i); for (j=0; j<(edge->GetNumberOfPoints()-1); j++) { p1 = edge->PointIds.GetId(j); p2 = edge->PointIds.GetId(j+1); mesh.GetCellEdgeNeighbors(cellId, p1, p2, cellIds); if ( cellIds.GetNumberOfIds() < 1 ) //generate strip { newStrips->InsertNextCell(2*(this->Resolution+1)); for (k=0; k<=this->Resolution; k++) { newStrips->InsertCellPoint(p2 + k*numPts); newStrips->InsertCellPoint(p1 + k*numPts); } } //if boundary edge } //for each sub-edge } //for each edge } //for each polygon or triangle strip } //for each cell // // Update ourselves and release memory // output->SetPoints(newPts); newPts->Delete(); if ( newLines ) { output->SetLines(newLines); newLines->Delete(); } if ( newPolys ) { output->SetPolys(newPolys); newPolys->Delete(); } output->SetStrips(newStrips); newStrips->Delete(); output->Squeeze(); } void vtkRotationalExtrusionFilter::PrintSelf(ostream& os, vtkIndent indent) { vtkPolyToPolyFilter::PrintSelf(os,indent); os << indent << "Resolution: " << this->Resolution << "\n"; os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n"); os << indent << "Angle: " << this->Angle << "\n"; os << indent << "Translation: " << this->Translation << "\n"; os << indent << "Delta Radius: " << this->DeltaRadius << "\n"; } <|endoftext|>
<commit_before>/* * IOBenchmark.cpp * * Created on: 01.02.2013 * Author: Christian Staudt ([email protected]) */ #ifndef NOGTEST #include "IOBenchmark.h" #include "../RasterReader.h" #include "../../generators/Quadtree/QuadtreePolarEuclid.h" #include "../../geometric/HyperbolicSpace.h" namespace NetworKit { TEST_F(IOBenchmark, timeMETISGraphReader) { std::string path = ""; std::cout << "[INPUT] .graph file path >" << std::endl; std::getline(std::cin, path); Aux::Timer runtime; INFO("[BEGIN] reading graph: " , path); runtime.start(); METISGraphReader reader; Graph G = reader.read(path); runtime.stop(); INFO("[DONE] reading graph " , runtime.elapsedTag()); EXPECT_TRUE(! G.isEmpty()); } TEST_F(IOBenchmark, benchRasterReader) { double normalizationFactor = 0.05; RasterReader reader(normalizationFactor); std::vector<double> xcoords; std::vector<double> ycoords; Aux::Timer runtime; std::vector<std::string> countries = {"deu", "usa"}; for (auto country: countries) { std::string path("input/" + country + "p00ag.asc"); // read raster file INFO("[BEGIN] reading raster data set: ", path); runtime.start(); std::tie(xcoords, ycoords) = reader.read(path); runtime.stop(); INFO("[DONE] reading raster data set " , runtime.elapsedTag()); EXPECT_EQ(xcoords.size(), ycoords.size()); //transform into polar coordinates runtime.start(); vector<double> angles(xcoords.size()); vector<double> radii(xcoords.size()); vector<index> content(xcoords.size()); double maxR = 0; for (index i = 0; i < xcoords.size(); i++) { HyperbolicSpace::cartesianToPolar(Point2D<double>(xcoords[i], ycoords[i]), angles[i], radii[i]); maxR = std::max(maxR, radii[i]); content[i] = i; } runtime.stop(); INFO("Converted coordinates", runtime.elapsedTag()); //define query function double T = 0.01; double thresholdDistance = maxR/1000; double beta = 1/T; auto edgeProb = [](double distance) -> double {return exp(-distance*200);}; //auto edgeProb = [beta, thresholdDistance](double distance) -> double {return 1 / (exp(beta*(distance-thresholdDistance)/2)+1);}; // perform range queries runtime.start(); QuadtreePolarEuclid<index> tree(angles, radii, content); runtime.stop(); INFO("Filled quadtree", runtime.elapsedTag()); uint64_t numQueries = 1000; long treeTotalNeighbours = 0; runtime.start(); for (uint64_t q = 0; q < numQueries; ++q) { vector<index> result; index comparison = Aux::Random::integer(xcoords.size()); Point2D<double> query(xcoords[comparison], ycoords[comparison]); tree.getElementsProbabilistically(query, edgeProb, result); treeTotalNeighbours += result.size(); } runtime.stop(); INFO("Completed ", numQueries, " quadtree queries with on average ", treeTotalNeighbours / numQueries, " neighbours", runtime.elapsedTag()); long naiveTotalNeighbours = 0; runtime.start(); for (uint64_t q = 0; q < numQueries; ++q) { vector<index> result; index comparison = Aux::Random::integer(xcoords.size()); double x = xcoords[comparison]; double y = ycoords[comparison]; for (index i = 0; i < xcoords.size(); i++) { double xdiff = xcoords[i] - x; double ydiff = ycoords[i] - y; double prob = edgeProb(pow(xdiff*xdiff+ydiff*ydiff , 0.5)); double random = Aux::Random::real(); if (random < prob) result.push_back(i); } naiveTotalNeighbours += result.size(); } runtime.stop(); INFO("Completed ", numQueries, " naive queries with on average ", naiveTotalNeighbours / numQueries, " neighbours", runtime.elapsedTag()); EXPECT_NEAR(treeTotalNeighbours, naiveTotalNeighbours, treeTotalNeighbours / 20); } } } /* namespace NetworKit */ #endif /* NOGTEST */ <commit_msg>10 test cases for the prizes of one!<commit_after>/* * IOBenchmark.cpp * * Created on: 01.02.2013 * Author: Christian Staudt ([email protected]) */ #ifndef NOGTEST #include "IOBenchmark.h" #include "../RasterReader.h" #include "../../generators/Quadtree/QuadtreePolarEuclid.h" #include "../../geometric/HyperbolicSpace.h" namespace NetworKit { TEST_F(IOBenchmark, timeMETISGraphReader) { std::string path = ""; std::cout << "[INPUT] .graph file path >" << std::endl; std::getline(std::cin, path); Aux::Timer runtime; INFO("[BEGIN] reading graph: " , path); runtime.start(); METISGraphReader reader; Graph G = reader.read(path); runtime.stop(); INFO("[DONE] reading graph " , runtime.elapsedTag()); EXPECT_TRUE(! G.isEmpty()); } TEST_F(IOBenchmark, benchRasterReader) { double normalizationFactor = 0.05; RasterReader reader(normalizationFactor); std::vector<double> xcoords; std::vector<double> ycoords; Aux::Timer runtime; std::vector<std::string> countries = {"deu", "usa"}; for (auto country: countries) { std::string path("input/" + country + "p00ag.asc"); // read raster file INFO("[BEGIN] reading raster data set: ", path); runtime.start(); std::tie(xcoords, ycoords) = reader.read(path); runtime.stop(); INFO("[DONE] reading raster data set " , runtime.elapsedTag()); EXPECT_EQ(xcoords.size(), ycoords.size()); count numRuns = 10; for (index run = 0; run < numRuns; run++) { //transform into polar coordinates runtime.start(); vector<double> angles(xcoords.size()); vector<double> radii(xcoords.size()); vector<index> content(xcoords.size()); double maxR = 0; for (index i = 0; i < xcoords.size(); i++) { HyperbolicSpace::cartesianToPolar(Point2D<double>(xcoords[i], ycoords[i]), angles[i], radii[i]); maxR = std::max(maxR, radii[i]); content[i] = i; } runtime.stop(); INFO("Converted coordinates", runtime.elapsedTag()); //define query function double T = 0.01; double thresholdDistance = maxR/1000; double beta = 1/T; auto edgeProb = [](double distance) -> double {return exp(-(distance*200+5));}; //auto edgeProb = [beta, thresholdDistance](double distance) -> double {return 1 / (exp(beta*(distance-thresholdDistance)/2)+1);}; // perform range queries runtime.start(); QuadtreePolarEuclid<index> tree(angles, radii, content); runtime.stop(); INFO("Filled quadtree", runtime.elapsedTag()); uint64_t numQueries = 1000; long treeTotalNeighbours = 0; runtime.start(); for (uint64_t q = 0; q < numQueries; ++q) { vector<index> result; index comparison = Aux::Random::integer(xcoords.size()); Point2D<double> query(xcoords[comparison], ycoords[comparison]); tree.getElementsProbabilistically(query, edgeProb, result); treeTotalNeighbours += result.size(); } runtime.stop(); INFO("Completed ", numQueries, " quadtree queries with on average ", treeTotalNeighbours / numQueries, " neighbours", runtime.elapsedTag()); long naiveTotalNeighbours = 0; runtime.start(); for (uint64_t q = 0; q < numQueries; ++q) { vector<index> result; index comparison = Aux::Random::integer(xcoords.size()); double x = xcoords[comparison]; double y = ycoords[comparison]; for (index i = 0; i < xcoords.size(); i++) { double xdiff = xcoords[i] - x; double ydiff = ycoords[i] - y; double prob = edgeProb(pow(xdiff*xdiff+ydiff*ydiff , 0.5)); double random = Aux::Random::real(); if (random < prob) result.push_back(i); } naiveTotalNeighbours += result.size(); } runtime.stop(); INFO("Completed ", numQueries, " naive queries with on average ", naiveTotalNeighbours / numQueries, " neighbours", runtime.elapsedTag()); EXPECT_NEAR(treeTotalNeighbours, naiveTotalNeighbours, treeTotalNeighbours / 10); } } } } /* namespace NetworKit */ #endif /* NOGTEST */ <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/tab_contents/tab_contents_observer.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/tab_contents.h" void TabContentsObserver::NavigateToPendingEntry() { } void TabContentsObserver::DidNavigateMainFramePostCommit( const NavigationController::LoadCommittedDetails& details, const ViewHostMsg_FrameNavigate_Params& params) { } void TabContentsObserver::DidNavigateAnyFramePostCommit( const NavigationController::LoadCommittedDetails& details, const ViewHostMsg_FrameNavigate_Params& params) { } void TabContentsObserver::OnProvisionalChangeToMainFrameUrl(const GURL& url) { } void TabContentsObserver::DidStartLoading() { } void TabContentsObserver::DidStopLoading() { } TabContentsObserver::TabContentsObserver(TabContents* tab_contents) : tab_contents_(tab_contents), routing_id_(tab_contents->render_view_host()->routing_id()) { tab_contents_->AddObserver(this); } TabContentsObserver::~TabContentsObserver() { if (tab_contents_) tab_contents_->RemoveObserver(this); } void TabContentsObserver::OnTabContentsDestroyed(TabContents* tab) { } bool TabContentsObserver::OnMessageReceived(const IPC::Message& message) { return false; } bool TabContentsObserver::Send(IPC::Message* message) { if (!tab_contents_->render_view_host()) { delete message; return false; } return tab_contents_->render_view_host()->Send(message); } void TabContentsObserver::TabContentsDestroyed() { // Do cleanup so that 'this' can safely be deleted from // OnTabContentsDestroyed. tab_contents_->RemoveObserver(this); TabContents* tab = tab_contents_; tab_contents_ = NULL; OnTabContentsDestroyed(tab); } <commit_msg>Fix crash in TabContentsObserver::Send on TabContents shutdown.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/tab_contents/tab_contents_observer.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/tab_contents.h" void TabContentsObserver::NavigateToPendingEntry() { } void TabContentsObserver::DidNavigateMainFramePostCommit( const NavigationController::LoadCommittedDetails& details, const ViewHostMsg_FrameNavigate_Params& params) { } void TabContentsObserver::DidNavigateAnyFramePostCommit( const NavigationController::LoadCommittedDetails& details, const ViewHostMsg_FrameNavigate_Params& params) { } void TabContentsObserver::OnProvisionalChangeToMainFrameUrl(const GURL& url) { } void TabContentsObserver::DidStartLoading() { } void TabContentsObserver::DidStopLoading() { } TabContentsObserver::TabContentsObserver(TabContents* tab_contents) : tab_contents_(tab_contents), routing_id_(tab_contents->render_view_host()->routing_id()) { tab_contents_->AddObserver(this); } TabContentsObserver::~TabContentsObserver() { if (tab_contents_) tab_contents_->RemoveObserver(this); } void TabContentsObserver::OnTabContentsDestroyed(TabContents* tab) { } bool TabContentsObserver::OnMessageReceived(const IPC::Message& message) { return false; } bool TabContentsObserver::Send(IPC::Message* message) { if (!tab_contents_ || !tab_contents_->render_view_host()) { delete message; return false; } return tab_contents_->render_view_host()->Send(message); } void TabContentsObserver::TabContentsDestroyed() { // Do cleanup so that 'this' can safely be deleted from // OnTabContentsDestroyed. tab_contents_->RemoveObserver(this); TabContents* tab = tab_contents_; tab_contents_ = NULL; OnTabContentsDestroyed(tab); } <|endoftext|>
<commit_before>#include "orrerybody.hpp" #include "units.hpp" namespace sim { orrery_body_vec_t load_debugging_orrery() { /* std::string name, std::string description, double GM, double radius, double ra, double dec, double rotational_rate, double orbit_radius, // for the debugging version double orbit_rate */ orrery_body_vec_t orrery = { { "Star", "The center of the solar system", 1, // GM 1, // radius 0.0, 0.0, 0.5, // ra, dec, rotation 0.0, // orbit radius 0.0 // orbital rate }, { "Planet0", "A barren wasteland", 1, // GM 1, // radius 0.0, 0.0, 0.5, // ra, dec, rotation 1.0_AU, // orbit radius 0.1 // orbital rate }, { "Planet1", "The first warring clan", 0.1, // GM 0.1, // radius 0.0, 0.0, 0.5, // ra, dec, rotation 10.0_AU, // orbit radius 0.05 // orbital rate }, { "Planet2", "The second warring clan", 0.1, // GM 0.05, // radius 0.0, 0.0, 0.5, // ra, dec, rotation 40.0_AU, // orbit radius 0.01 // orbital rate }, }; return orrery; } }<commit_msg>entered solar system data for debugging orrery<commit_after>#include "orrerybody.hpp" #include "units.hpp" namespace sim { orrery_body_vec_t load_debugging_orrery() { /* std::string name, std::string description, double GM, double radius, double ra, double dec, double rotational_rate, double orbit_radius, // for the debugging version double orbit_rate */ orrery_body_vec_t orrery = { { "Sun", "The center of the solar system", 1.33e20, // GM 1, // radius 0.0, 0.0, 0.5, // ra, dec, rotation 0.0, // orbit radius 0.0 // orbital rate }, { "Mercury", "A barren wasteland", 2.2e13, // GM 1, // radius 0.0, 0.0, 0.5, // ra, dec, rotation 57.91e9, // orbit radius 87.96 // orbital rate }, { "Venus", "A barren wasteland", 3.25e14, // GM 1, // radius 0.0, 0.0, 0.5, // ra, dec, rotation 108.21e9, // orbit radius 224.701 // orbital rate }, { "Earth", "A barren wasteland", 3.99e14, // GM 1, // radius 0.0, 0.0, 0.5, // ra, dec, rotation 149.6e9, // orbit radius 365.256 // orbital rate }, { "Mars", "A barren wasteland", 4.28e13, // GM 1, // radius 0.0, 0.0, 0.5, // ra, dec, rotation 227.92e9, // orbit radius 686.98 // orbital rate }, { "Jupiter", "A barren wasteland", 1.267e17, // GM 1, // radius 0.0, 0.0, 0.5, // ra, dec, rotation 778.57e9, // orbit radius 4332.59 // orbital rate }, { "Saturn", "A barren wasteland", 3.79e16, // GM 1, // radius 0.0, 0.0, 0.5, // ra, dec, rotation 1433.53e9, // orbit radius 10759.2 // orbital rate }, { "Uranus", "A barren wasteland", 5.79e15, // GM 1, // radius 0.0, 0.0, 0.5, // ra, dec, rotation 2872.46e9, // orbit radius 30685 // orbital rate }, { "Neptune", "The first warring clan", 6.84e15, // GM 0.1, // radius 0.0, 0.0, 0.5, // ra, dec, rotation 4495.06e9, // orbit radius 60189.0 // orbital rate }, { "Pluto", "The second warring clan", 8.71e11, // GM 0.05, // radius 0.0, 0.0, 0.5, // ra, dec, rotation 5869.66e9, // orbit radius 90465 // orbital rate }, { "Eris", "The second warring clan", 1.11e12, // GM 0.05, // radius 0.0, 0.0, 0.5, // ra, dec, rotation 97.651_AU, // orbit radius 203830.0 // orbital rate }, }; return orrery; } }<|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2005 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osg/Notify> #include <string> #include <iostream> #include <fstream> using namespace std; osg::NotifySeverity g_NotifyLevel = osg::NOTICE; void osg::setNotifyLevel(osg::NotifySeverity severity) { osg::initNotifyLevel(); g_NotifyLevel = severity; } osg::NotifySeverity osg::getNotifyLevel() { osg::initNotifyLevel(); return g_NotifyLevel; } bool osg::initNotifyLevel() { static bool s_NotifyInit = false; if (s_NotifyInit) return true; s_NotifyInit = true; // g_NotifyLevel // ============= g_NotifyLevel = osg::NOTICE; // Default value char* OSGNOTIFYLEVEL=getenv("OSG_NOTIFY_LEVEL"); if (!OSGNOTIFYLEVEL) OSGNOTIFYLEVEL=getenv("OSGNOTIFYLEVEL"); if(OSGNOTIFYLEVEL) { std::string stringOSGNOTIFYLEVEL(OSGNOTIFYLEVEL); // Convert to upper case for(std::string::iterator i=stringOSGNOTIFYLEVEL.begin(); i!=stringOSGNOTIFYLEVEL.end(); ++i) { *i=toupper(*i); } if(stringOSGNOTIFYLEVEL.find("ALWAYS")!=std::string::npos) g_NotifyLevel=osg::ALWAYS; else if(stringOSGNOTIFYLEVEL.find("FATAL")!=std::string::npos) g_NotifyLevel=osg::FATAL; else if(stringOSGNOTIFYLEVEL.find("WARN")!=std::string::npos) g_NotifyLevel=osg::WARN; else if(stringOSGNOTIFYLEVEL.find("NOTICE")!=std::string::npos) g_NotifyLevel=osg::NOTICE; else if(stringOSGNOTIFYLEVEL.find("DEBUG_INFO")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO; else if(stringOSGNOTIFYLEVEL.find("DEBUG_FP")!=std::string::npos) g_NotifyLevel=osg::DEBUG_FP; else if(stringOSGNOTIFYLEVEL.find("DEBUG")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO; else if(stringOSGNOTIFYLEVEL.find("INFO")!=std::string::npos) g_NotifyLevel=osg::INFO; else std::cout << "Warning: invalid OSG_NOTIFY_LEVEL set ("<<stringOSGNOTIFYLEVEL<<")"<<std::endl; } return true; } bool osg::isNotifyEnabled( osg::NotifySeverity severity ) { return severity<=g_NotifyLevel; } #if defined(WIN32) && !(defined(__CYGWIN__) || defined(__MINGW32__)) const char* NullStreamName = "nul"; #else const char* NullStreamName = "/dev/null"; #endif std::ostream& osg::notify(const osg::NotifySeverity severity) { // set up global notify null stream for inline notify static std::ofstream s_NotifyNulStream(NullStreamName); static bool initialized = false; if (!initialized) { std::cerr<<""; // dummy op to force construction of cerr, before a reference is passed back to calling code. std::cout<<""; // dummy op to force construction of cout, before a reference is passed back to calling code. initialized = osg::initNotifyLevel(); } if (severity<=g_NotifyLevel) { if (severity<=osg::WARN) return std::cerr; else return std::cout; } return s_NotifyNulStream; } <commit_msg>Moved the intialization variable reset to end of the init funciton to avoid multi-thread initialization from producing different results.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2005 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osg/Notify> #include <string> #include <iostream> #include <fstream> using namespace std; osg::NotifySeverity g_NotifyLevel = osg::NOTICE; void osg::setNotifyLevel(osg::NotifySeverity severity) { osg::initNotifyLevel(); g_NotifyLevel = severity; } osg::NotifySeverity osg::getNotifyLevel() { osg::initNotifyLevel(); return g_NotifyLevel; } bool osg::initNotifyLevel() { static bool s_NotifyInit = false; if (s_NotifyInit) return true; // g_NotifyLevel // ============= g_NotifyLevel = osg::NOTICE; // Default value char* OSGNOTIFYLEVEL=getenv("OSG_NOTIFY_LEVEL"); if (!OSGNOTIFYLEVEL) OSGNOTIFYLEVEL=getenv("OSGNOTIFYLEVEL"); if(OSGNOTIFYLEVEL) { std::string stringOSGNOTIFYLEVEL(OSGNOTIFYLEVEL); // Convert to upper case for(std::string::iterator i=stringOSGNOTIFYLEVEL.begin(); i!=stringOSGNOTIFYLEVEL.end(); ++i) { *i=toupper(*i); } if(stringOSGNOTIFYLEVEL.find("ALWAYS")!=std::string::npos) g_NotifyLevel=osg::ALWAYS; else if(stringOSGNOTIFYLEVEL.find("FATAL")!=std::string::npos) g_NotifyLevel=osg::FATAL; else if(stringOSGNOTIFYLEVEL.find("WARN")!=std::string::npos) g_NotifyLevel=osg::WARN; else if(stringOSGNOTIFYLEVEL.find("NOTICE")!=std::string::npos) g_NotifyLevel=osg::NOTICE; else if(stringOSGNOTIFYLEVEL.find("DEBUG_INFO")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO; else if(stringOSGNOTIFYLEVEL.find("DEBUG_FP")!=std::string::npos) g_NotifyLevel=osg::DEBUG_FP; else if(stringOSGNOTIFYLEVEL.find("DEBUG")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO; else if(stringOSGNOTIFYLEVEL.find("INFO")!=std::string::npos) g_NotifyLevel=osg::INFO; else std::cout << "Warning: invalid OSG_NOTIFY_LEVEL set ("<<stringOSGNOTIFYLEVEL<<")"<<std::endl; } s_NotifyInit = true; return true; } bool osg::isNotifyEnabled( osg::NotifySeverity severity ) { return severity<=g_NotifyLevel; } #if defined(WIN32) && !(defined(__CYGWIN__) || defined(__MINGW32__)) const char* NullStreamName = "nul"; #else const char* NullStreamName = "/dev/null"; #endif std::ostream& osg::notify(const osg::NotifySeverity severity) { // set up global notify null stream for inline notify static std::ofstream s_NotifyNulStream(NullStreamName); static bool initialized = false; if (!initialized) { std::cerr<<""; // dummy op to force construction of cerr, before a reference is passed back to calling code. std::cout<<""; // dummy op to force construction of cout, before a reference is passed back to calling code. initialized = osg::initNotifyLevel(); } if (severity<=g_NotifyLevel) { if (severity<=osg::WARN) return std::cerr; else return std::cout; } return s_NotifyNulStream; } <|endoftext|>
<commit_before>// // Copyright (c) 2014 CNRS // Authors: Florent Lamiraux // // This file is part of hpp-core // hpp-core 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. // // hpp-core 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core If not, see // <http://www.gnu.org/licenses/>. #include <hpp/core/path-vector.hh> namespace hpp { namespace core { std::size_t PathVector::rankAtParam (const value_type& param, value_type& localParam) const { std::size_t res = 0; localParam = param; bool finished = false; while (res < paths_.size () - 1 && !finished) { if (localParam > paths_ [res]->length ()) { localParam -= paths_ [res]->length (); res ++; } else { finished = true; } } if (localParam > paths_ [res]->length ()) { if (res != paths_.size () -1) { throw std::runtime_error ("localparam out of range."); } localParam = paths_ [res]->timeRange ().second; } localParam += paths_ [res]->timeRange ().first; return res; } void PathVector::appendPath (const PathPtr_t& path) { paths_.push_back (path); timeRange_.second += path->length (); } PathPtr_t PathVector::pathAtRank (std::size_t rank) const { PathPtr_t copy; if (constraints ()) { if (paths_ [rank]->constraints ()) { throw std::runtime_error ("Attempt to extract a path from a path vector where both " "are subject to constraints. This is not supported."); } else { ConstraintPtr_t constraintCopy (constraints ()->copy ()); HPP_STATIC_CAST_REF_CHECK (ConstraintSet, *constraintCopy); copy = paths_ [rank]->copy (HPP_STATIC_PTR_CAST (ConstraintSet, constraintCopy)); } } else { copy = paths_ [rank]->copy (); } return copy; } void PathVector::concatenate (const PathVector& path) { for (std::size_t i=0; i<path.numberPaths (); ++i) { appendPath (path.pathAtRank (i)->copy ()); } } bool PathVector::impl_compute (ConfigurationOut_t result, value_type t) const { // Find direct path in vector corresponding to parameter. size_t rank; value_type localParam; rank = rankAtParam (t, localParam); PathPtr_t subpath = paths_ [rank]; return (*subpath) (result, localParam); } PathPtr_t PathVector::extract (const interval_t& subInterval) const { using std::make_pair; PathVectorPtr_t path = create (outputSize (), outputDerivativeSize ()); bool reversed = subInterval.first > subInterval.second ? true : false; if (reversed) { value_type tmin = subInterval.second; value_type tmax = subInterval.first; value_type localtmin, localtmax; int imin = rankAtParam (tmin, localtmin); int imax = rankAtParam (tmax, localtmax); value_type t1min, t1max; int i = imax; do { t1min = paths_ [i]->timeRange ().second; t1max = paths_ [i]->timeRange ().first; if (i == imax) { t1min = localtmax; } if (i == imin) { t1max = localtmin; } path->appendPath (paths_ [i]->extract (make_pair (t1min, t1max))); --i; } while (i >= imin); } else { value_type tmin = subInterval.first; value_type tmax = subInterval.second; value_type localtmin, localtmax; std::size_t imin = rankAtParam (tmin, localtmin); std::size_t imax = rankAtParam (tmax, localtmax); value_type t1min, t1max; std::size_t i = imin; do { t1min = paths_ [i]->timeRange ().first; t1max = paths_ [i]->timeRange ().second; if (i == imin) { t1min = localtmin; } if (i == imax) { t1max = localtmax; } path->appendPath (paths_ [i]->extract (make_pair (t1min, t1max))); ++i; } while (i <= imax); } return path; } } // namespace core } // namespace hpp <commit_msg>Fix compilation warning in 64bit.<commit_after>// // Copyright (c) 2014 CNRS // Authors: Florent Lamiraux // // This file is part of hpp-core // hpp-core 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. // // hpp-core 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core If not, see // <http://www.gnu.org/licenses/>. #include <hpp/core/path-vector.hh> namespace hpp { namespace core { std::size_t PathVector::rankAtParam (const value_type& param, value_type& localParam) const { std::size_t res = 0; localParam = param; bool finished = false; while (res < paths_.size () - 1 && !finished) { if (localParam > paths_ [res]->length ()) { localParam -= paths_ [res]->length (); res ++; } else { finished = true; } } if (localParam > paths_ [res]->length ()) { if (res != paths_.size () -1) { throw std::runtime_error ("localparam out of range."); } localParam = paths_ [res]->timeRange ().second; } localParam += paths_ [res]->timeRange ().first; return res; } void PathVector::appendPath (const PathPtr_t& path) { paths_.push_back (path); timeRange_.second += path->length (); } PathPtr_t PathVector::pathAtRank (std::size_t rank) const { PathPtr_t copy; if (constraints ()) { if (paths_ [rank]->constraints ()) { throw std::runtime_error ("Attempt to extract a path from a path vector where both " "are subject to constraints. This is not supported."); } else { ConstraintPtr_t constraintCopy (constraints ()->copy ()); HPP_STATIC_CAST_REF_CHECK (ConstraintSet, *constraintCopy); copy = paths_ [rank]->copy (HPP_STATIC_PTR_CAST (ConstraintSet, constraintCopy)); } } else { copy = paths_ [rank]->copy (); } return copy; } void PathVector::concatenate (const PathVector& path) { for (std::size_t i=0; i<path.numberPaths (); ++i) { appendPath (path.pathAtRank (i)->copy ()); } } bool PathVector::impl_compute (ConfigurationOut_t result, value_type t) const { // Find direct path in vector corresponding to parameter. size_t rank; value_type localParam; rank = rankAtParam (t, localParam); PathPtr_t subpath = paths_ [rank]; return (*subpath) (result, localParam); } PathPtr_t PathVector::extract (const interval_t& subInterval) const { using std::make_pair; PathVectorPtr_t path = create (outputSize (), outputDerivativeSize ()); bool reversed = subInterval.first > subInterval.second ? true : false; if (reversed) { value_type tmin = subInterval.second; value_type tmax = subInterval.first; value_type localtmin, localtmax; std::size_t imin = rankAtParam (tmin, localtmin); std::size_t imax = rankAtParam (tmax, localtmax); value_type t1min, t1max; std::size_t i = imax; do { t1min = paths_ [i]->timeRange ().second; t1max = paths_ [i]->timeRange ().first; if (i == imax) { t1min = localtmax; } if (i == imin) { t1max = localtmin; } path->appendPath (paths_ [i]->extract (make_pair (t1min, t1max))); --i; } while (i >= imin); } else { value_type tmin = subInterval.first; value_type tmax = subInterval.second; value_type localtmin, localtmax; std::size_t imin = rankAtParam (tmin, localtmin); std::size_t imax = rankAtParam (tmax, localtmax); value_type t1min, t1max; std::size_t i = imin; do { t1min = paths_ [i]->timeRange ().first; t1max = paths_ [i]->timeRange ().second; if (i == imin) { t1min = localtmin; } if (i == imax) { t1max = localtmax; } path->appendPath (paths_ [i]->extract (make_pair (t1min, t1max))); ++i; } while (i <= imax); } return path; } } // namespace core } // namespace hpp <|endoftext|>
<commit_before>/* Copyright (C) 2012 Aleix Pol Gonzalez <[email protected]> Copyright (C) 2013 Martin Klapetek <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "persondata.h" #include "personsmodel.h" #include "personitem.h" #include "personpluginmanager.h" #include "basepersonsdatasource.h" #include "datasourcewatcher.h" #include <Nepomuk2/Resource> #include <Nepomuk2/Query/Query> #include <Nepomuk2/ResourceManager> #include <Nepomuk2/ResourceWatcher> #include <Nepomuk2/Vocabulary/PIMO> #include <Nepomuk2/Vocabulary/NCO> #include <Nepomuk2/Vocabulary/NIE> #include <Nepomuk2/Variant> #include <Soprano/Model> #include <Soprano/Vocabulary/NAO> #include <Soprano/QueryResultIterator> #include <KDebug> #include <QPointer> using namespace Nepomuk2::Vocabulary; using namespace Soprano::Vocabulary; using namespace KPeople; namespace KPeople { class PersonDataPrivate { public: PersonDataPrivate(PersonData *q) { dataSourceWatcher = new DataSourceWatcher(q); q->connect(dataSourceWatcher, SIGNAL(contactChanged(QUrl)), q, SIGNAL(dataChanged())); } QUrl uri; QPointer<Nepomuk2::ResourceWatcher> watcher; DataSourceWatcher *dataSourceWatcher; Nepomuk2::Resource personResource; QList<Nepomuk2::Resource> contactResources; }; } PersonDataPtr PersonData::createFromUri(const QUrl &uri) { PersonDataPtr person(new PersonData); person->loadUri(uri); return person; } PersonDataPtr PersonData::createFromContactId(const QString &contactId) { PersonDataPtr person(new PersonData); person->loadContact(contactId); return person; } PersonData::PersonData(QObject *parent) : QObject(parent), d_ptr(new PersonDataPrivate(this)) { } PersonData::~PersonData() { delete d_ptr; } void PersonData::loadContact(const QString &id) { QString query = QString::fromUtf8( "select DISTINCT ?uri " "WHERE { " "?uri a nco:PersonContact. " "?uri nco:hasContactMedium ?a . " "?a ?b \"%1\"^^xsd:string . " "}").arg(id); Soprano::Model *model = Nepomuk2::ResourceManager::instance()->mainModel(); Soprano::QueryResultIterator it = model->executeQuery(query, Soprano::Query::QueryLanguageSparql); QString uri; while (it.next()) { uri = it[0].uri().toString(); break; } loadUri(uri); } QUrl PersonData::uri() const { Q_D(const PersonData); return d->uri; } void PersonData::loadUri(const QUrl &uri) { Q_D(PersonData); d->uri = uri; d->personResource = Nepomuk2::Resource(); Nepomuk2::Resource r(uri); d->watcher = new Nepomuk2::ResourceWatcher(this); if (r.type() == PIMO::Person()) { d->personResource = r; d->contactResources = r.property(PIMO::groundingOccurrence()).toResourceList(); Q_FOREACH (Nepomuk2::Resource res, d->contactResources) { //cannot use const here as we're modifying the resource d->watcher->addResource(res); res.setWatchEnabled(true); } } else { d->contactResources = QList<Nepomuk2::Resource>() << r; } r.setWatchEnabled(true); d->watcher->addResource(r); connect(d->watcher, SIGNAL(propertyChanged(Nepomuk2::Resource,Nepomuk2::Types::Property,QVariantList,QVariantList)), this, SIGNAL(dataChanged())); d->watcher->start(); //watch for IM changes Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) { Q_FOREACH (const Nepomuk2::Resource &im, resource.property(NCO::hasIMAccount()).toResourceList()) { d->dataSourceWatcher->watchContact(im.property(NCO::imID()).toString(), resource.uri()); } } emit dataChanged(); } bool PersonData::isValid() const { Q_D(const PersonData); return !d->contactResources.isEmpty(); } QString PersonData::status() const { Q_D(const PersonData); QStringList presenceList; Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) { if (resource.hasProperty(NCO::hasIMAccount())) { QString imID = resource.property(NCO::hasIMAccount()).toResource().property(NCO::imID()).toString(); presenceList << PersonPluginManager::presencePlugin()->dataForContact(imID, PersonsModel::PresenceTypeRole).toString(); } } return findMostOnlinePresence(presenceList); } QUrl PersonData::avatar() const { Q_D(const PersonData); Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) { if (resource.hasProperty(NCO::photo())) { return resource.property(NCO::photo()).toResource().property(NIE::url()).toUrl(); } } return QUrl(); } QString PersonData::name() const { Q_D(const PersonData); if (d->contactResources.isEmpty()) { return QString(); } QString label; //simply pick the first for now Nepomuk2::Resource r = d->contactResources.first(); if (r.hasProperty(NCO::nickname())) { label = r.property(NCO::nickname()).toString(); } else if (r.hasProperty(NAO::prefLabel())) { label = r.property(NAO::prefLabel()).toString(); } else if (r.hasProperty(NCO::fullname())) { label = r.property(NCO::fullname()).toString(); } else if (r.hasProperty(NCO::hasIMAccount())) { label = r.property(NCO::hasIMAccount()).toResource().property(NCO::imNickname()).toString(); } else if (r.hasProperty(NCO::hasEmailAddress())) { label = r.property(NCO::hasEmailAddress()).toResource().property(NCO::emailAddress()).toString(); } else if (r.hasProperty(NCO::hasPhoneNumber())) { label = r.property(NCO::hasPhoneNumber()).toResource().property(NCO::phoneNumber()).toString(); } if (!label.isEmpty()) { return label; } return r.property(NCO::hasContactMedium()).toResource().genericLabel(); } QStringList PersonData::emails() const { Q_D(const PersonData); QStringList emails; Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) { Q_FOREACH (const Nepomuk2::Resource &email, resource.property(NCO::hasEmailAddress()).toResourceList()) { emails << email.property(NCO::emailAddress()).toString(); } } return emails; } QStringList PersonData::phones() const { Q_D(const PersonData); QStringList phones; Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) { Q_FOREACH (const Nepomuk2::Resource &phone, resource.property(NCO::hasPhoneNumber()).toResourceList()) { phones << phone.property(NCO::phoneNumber()).toString(); } } return phones; } QStringList PersonData::imAccounts() const { Q_D(const PersonData); QStringList ims; Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) { Q_FOREACH (const Nepomuk2::Resource &im, resource.property(NCO::hasIMAccount()).toResourceList()) { ims << im.property(NCO::imAccountType()).toString(); ims << im.property(NCO::imNickname()).toString(); ims << im.property(NCO::imID()).toString(); } } return ims; } KDateTime PersonData::birthday() const { Q_D(const PersonData); //we'll go through all the dates we have and from every date we //get msecs from epoch and then we'll check whichever is greater //If the date has only month and a year, it will be counted //to 1st day of that month. If the real date is actually 15th day, //it means the more complete date will have more msecs from the epoch KDateTime bd; Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) { KDateTime bdTemp(resource.property(NCO::birthDate()).toDateTime()); if (bdTemp.isValid() && bdTemp.dateTime().toMSecsSinceEpoch() > bd.dateTime().toMSecsSinceEpoch()) { bd = bdTemp; } } return bd; } QStringList PersonData::groups() const { Q_D(const PersonData); QStringList groups; Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) { Nepomuk2::Variant groupProperties = resource.property(NCO::belongsToGroup()); if (!groupProperties.isValid()) { continue; } Q_FOREACH (const Nepomuk2::Resource &groupResource, groupProperties.toResourceList()) { groups << groupResource.property(NCO::contactGroupName()).toString(); } } return groups; } QList< Nepomuk2::Resource > PersonData::contactResources() const { Q_D(const PersonData); return d->contactResources; } bool PersonData::isPerson() const { Q_D(const PersonData); return d->personResource.isValid(); } QString PersonData::findMostOnlinePresence(const QStringList &presences) const { if (presences.contains("available")) { return "available"; } if (presences.contains("away")) { return "away"; } if (presences.contains("busy") || presences.contains("dnd")) { return "busy"; } if (presences.contains("xa")) { return "xa"; } return "offline"; } <commit_msg>Return only imIDs in imAccounts<commit_after>/* Copyright (C) 2012 Aleix Pol Gonzalez <[email protected]> Copyright (C) 2013 Martin Klapetek <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "persondata.h" #include "personsmodel.h" #include "personitem.h" #include "personpluginmanager.h" #include "basepersonsdatasource.h" #include "datasourcewatcher.h" #include <Nepomuk2/Resource> #include <Nepomuk2/Query/Query> #include <Nepomuk2/ResourceManager> #include <Nepomuk2/ResourceWatcher> #include <Nepomuk2/Vocabulary/PIMO> #include <Nepomuk2/Vocabulary/NCO> #include <Nepomuk2/Vocabulary/NIE> #include <Nepomuk2/Variant> #include <Soprano/Model> #include <Soprano/Vocabulary/NAO> #include <Soprano/QueryResultIterator> #include <KDebug> #include <QPointer> using namespace Nepomuk2::Vocabulary; using namespace Soprano::Vocabulary; using namespace KPeople; namespace KPeople { class PersonDataPrivate { public: PersonDataPrivate(PersonData *q) { dataSourceWatcher = new DataSourceWatcher(q); q->connect(dataSourceWatcher, SIGNAL(contactChanged(QUrl)), q, SIGNAL(dataChanged())); } QUrl uri; QPointer<Nepomuk2::ResourceWatcher> watcher; DataSourceWatcher *dataSourceWatcher; Nepomuk2::Resource personResource; QList<Nepomuk2::Resource> contactResources; }; } PersonDataPtr PersonData::createFromUri(const QUrl &uri) { PersonDataPtr person(new PersonData); person->loadUri(uri); return person; } PersonDataPtr PersonData::createFromContactId(const QString &contactId) { PersonDataPtr person(new PersonData); person->loadContact(contactId); return person; } PersonData::PersonData(QObject *parent) : QObject(parent), d_ptr(new PersonDataPrivate(this)) { } PersonData::~PersonData() { delete d_ptr; } void PersonData::loadContact(const QString &id) { QString query = QString::fromUtf8( "select DISTINCT ?uri " "WHERE { " "?uri a nco:PersonContact. " "?uri nco:hasContactMedium ?a . " "?a ?b \"%1\"^^xsd:string . " "}").arg(id); Soprano::Model *model = Nepomuk2::ResourceManager::instance()->mainModel(); Soprano::QueryResultIterator it = model->executeQuery(query, Soprano::Query::QueryLanguageSparql); QString uri; while (it.next()) { uri = it[0].uri().toString(); break; } loadUri(uri); } QUrl PersonData::uri() const { Q_D(const PersonData); return d->uri; } void PersonData::loadUri(const QUrl &uri) { Q_D(PersonData); d->uri = uri; d->personResource = Nepomuk2::Resource(); Nepomuk2::Resource r(uri); d->watcher = new Nepomuk2::ResourceWatcher(this); if (r.type() == PIMO::Person()) { d->personResource = r; d->contactResources = r.property(PIMO::groundingOccurrence()).toResourceList(); Q_FOREACH (Nepomuk2::Resource res, d->contactResources) { //cannot use const here as we're modifying the resource d->watcher->addResource(res); res.setWatchEnabled(true); } } else { d->contactResources = QList<Nepomuk2::Resource>() << r; } r.setWatchEnabled(true); d->watcher->addResource(r); connect(d->watcher, SIGNAL(propertyChanged(Nepomuk2::Resource,Nepomuk2::Types::Property,QVariantList,QVariantList)), this, SIGNAL(dataChanged())); d->watcher->start(); //watch for IM changes Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) { Q_FOREACH (const Nepomuk2::Resource &im, resource.property(NCO::hasIMAccount()).toResourceList()) { d->dataSourceWatcher->watchContact(im.property(NCO::imID()).toString(), resource.uri()); } } emit dataChanged(); } bool PersonData::isValid() const { Q_D(const PersonData); return !d->contactResources.isEmpty(); } QString PersonData::status() const { Q_D(const PersonData); QStringList presenceList; Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) { if (resource.hasProperty(NCO::hasIMAccount())) { QString imID = resource.property(NCO::hasIMAccount()).toResource().property(NCO::imID()).toString(); presenceList << PersonPluginManager::presencePlugin()->dataForContact(imID, PersonsModel::PresenceTypeRole).toString(); } } return findMostOnlinePresence(presenceList); } QUrl PersonData::avatar() const { Q_D(const PersonData); Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) { if (resource.hasProperty(NCO::photo())) { return resource.property(NCO::photo()).toResource().property(NIE::url()).toUrl(); } } return QUrl(); } QString PersonData::name() const { Q_D(const PersonData); if (d->contactResources.isEmpty()) { return QString(); } QString label; //simply pick the first for now Nepomuk2::Resource r = d->contactResources.first(); if (r.hasProperty(NCO::nickname())) { label = r.property(NCO::nickname()).toString(); } else if (r.hasProperty(NAO::prefLabel())) { label = r.property(NAO::prefLabel()).toString(); } else if (r.hasProperty(NCO::fullname())) { label = r.property(NCO::fullname()).toString(); } else if (r.hasProperty(NCO::hasIMAccount())) { label = r.property(NCO::hasIMAccount()).toResource().property(NCO::imNickname()).toString(); } else if (r.hasProperty(NCO::hasEmailAddress())) { label = r.property(NCO::hasEmailAddress()).toResource().property(NCO::emailAddress()).toString(); } else if (r.hasProperty(NCO::hasPhoneNumber())) { label = r.property(NCO::hasPhoneNumber()).toResource().property(NCO::phoneNumber()).toString(); } if (!label.isEmpty()) { return label; } return r.property(NCO::hasContactMedium()).toResource().genericLabel(); } QStringList PersonData::emails() const { Q_D(const PersonData); QStringList emails; Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) { Q_FOREACH (const Nepomuk2::Resource &email, resource.property(NCO::hasEmailAddress()).toResourceList()) { emails << email.property(NCO::emailAddress()).toString(); } } return emails; } QStringList PersonData::phones() const { Q_D(const PersonData); QStringList phones; Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) { Q_FOREACH (const Nepomuk2::Resource &phone, resource.property(NCO::hasPhoneNumber()).toResourceList()) { phones << phone.property(NCO::phoneNumber()).toString(); } } return phones; } QStringList PersonData::imAccounts() const { Q_D(const PersonData); QStringList ims; Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) { Q_FOREACH (const Nepomuk2::Resource &im, resource.property(NCO::hasIMAccount()).toResourceList()) { ims << im.property(NCO::imID()).toString(); } } return ims; } KDateTime PersonData::birthday() const { Q_D(const PersonData); //we'll go through all the dates we have and from every date we //get msecs from epoch and then we'll check whichever is greater //If the date has only month and a year, it will be counted //to 1st day of that month. If the real date is actually 15th day, //it means the more complete date will have more msecs from the epoch KDateTime bd; Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) { KDateTime bdTemp(resource.property(NCO::birthDate()).toDateTime()); if (bdTemp.isValid() && bdTemp.dateTime().toMSecsSinceEpoch() > bd.dateTime().toMSecsSinceEpoch()) { bd = bdTemp; } } return bd; } QStringList PersonData::groups() const { Q_D(const PersonData); QStringList groups; Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) { Nepomuk2::Variant groupProperties = resource.property(NCO::belongsToGroup()); if (!groupProperties.isValid()) { continue; } Q_FOREACH (const Nepomuk2::Resource &groupResource, groupProperties.toResourceList()) { groups << groupResource.property(NCO::contactGroupName()).toString(); } } return groups; } QList< Nepomuk2::Resource > PersonData::contactResources() const { Q_D(const PersonData); return d->contactResources; } bool PersonData::isPerson() const { Q_D(const PersonData); return d->personResource.isValid(); } QString PersonData::findMostOnlinePresence(const QStringList &presences) const { if (presences.contains("available")) { return "available"; } if (presences.contains("away")) { return "away"; } if (presences.contains("busy") || presences.contains("dnd")) { return "busy"; } if (presences.contains("xa")) { return "xa"; } return "offline"; } <|endoftext|>
<commit_before>/* Persons Model Item Represents one person in the model Copyright (C) 2012 Martin Klapetek <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "personitem.h" #include "contactitem.h" #include <Nepomuk2/Vocabulary/PIMO> #include <Nepomuk2/Vocabulary/NCO> #include <Nepomuk2/Resource> #include <Nepomuk2/Variant> #include <Soprano/Vocabulary/NAO> #include <KDebug> PersonItem::PersonItem(const QUrl &personUri) { setData(personUri, PersonsModel::UriRole); } PersonItem::PersonItem(const Nepomuk2::Resource &person) { setData(person.uri(), PersonsModel::UriRole); setContacts(person.property(Nepomuk2::Vocabulary::PIMO::groundingOccurrence()).toUrlList()); kDebug() << "new person" << text() << rowCount(); } QVariant PersonItem::queryChildrenForRole(int role) const { QVariant ret; for (int i = 0; i < rowCount(); i++) { QVariant value = child(i)->data(role); if (!value.isNull()) { ret = value; break; } } return ret; } QVariantList PersonItem::queryChildrenForRoleList(int role) const { QVariantList ret; for (int i = 0; i < rowCount(); i++) { QVariant value = child(i)->data(role); if (value.type() == QVariant::List) { ret += value.toList(); } else if (!value.isNull()) { ret += value; } } return ret; } QVariant PersonItem::data(int role) const { if (role == PersonsModel::PresenceTypeRole) { //TODO: return most online presence } QVariantList ret; for (int i = 0; i < rowCount(); i++) { QVariant value = child(i)->data(role); if ((role == Qt::DisplayRole || role == Qt::DecorationRole || role == PersonsModel::UriRole) && !value.isNull()) { return value; } if (value.type() == QVariant::List) { ret += value.toList(); } else if (!value.isNull()) { ret += value; } } if (ret.isEmpty()) { //we need to return empty qvariant here, otherwise we'd get a qvariant //with empty qvariantlist, which would get parsed as non-empty qvariant return QVariant(); } return ret; } void PersonItem::removeContacts(const QList<QUrl> &contacts) { kDebug() << "remove contacts" << contacts; for (int i = 0; i < rowCount(); ) { QStandardItem *item = child(i); if (item && contacts.contains(item->data(PersonsModel::UriRole).toUrl())) { model()->invisibleRootItem()->appendRow(takeRow(i)); } else { ++i; } } emitDataChanged(); } void PersonItem::addContacts(const QList<QUrl> &_contacts) { QList<QUrl> contacts(_contacts); //get existing child-contacts and remove them from the new ones QVariantList uris = queryChildrenForRoleList(PersonsModel::UriRole); foreach (const QVariant &uri, uris) { contacts.removeOne(uri.toUrl()); } //query the model for the contacts, if they are present, then need to be just moved QList<QStandardItem*> toplevelContacts; foreach (const QUrl &uri, contacts) { QModelIndex contactIndex = qobject_cast<PersonsModel*>(model())->indexForUri(uri); if (contactIndex.isValid()) { toplevelContacts.append(qobject_cast<PersonsModel*>(model())->takeRow(contactIndex.row())); } } //append the moved contacts to this person and remove them from 'contacts' //so they are not added twice foreach (QStandardItem *contactItem, toplevelContacts) { //FIXME: we need to remove the fake person item here ContactItem *contact = dynamic_cast<ContactItem*>(contactItem); appendRow(contact); contacts.removeOne(contact->uri()); } QList<ContactItem*> rows; foreach (const QUrl &uri, contacts) { ContactItem *item = new ContactItem(uri); item->loadData(); appendRow(item); } emitDataChanged(); } void PersonItem::setContacts(const QList<QUrl> &contacts) { kDebug() << "set contacts" << contacts; if (contacts.isEmpty()) { //nothing to do here return; } if (hasChildren()) { QList<QUrl> toRemove; QVariantList uris = queryChildrenForRoleList(PersonsModel::UriRole); foreach (const QVariant &contact, uris) { if (!contacts.contains(contact.toUrl())) toRemove += contact.toUrl(); } removeContacts(toRemove); } QList<QUrl> toAdd; foreach (const QUrl &contact, contacts) { toAdd += contact; } addContacts(toAdd); Q_ASSERT(hasChildren()); } <commit_msg>Add a comment (forgot to stage with prev commit)<commit_after>/* Persons Model Item Represents one person in the model Copyright (C) 2012 Martin Klapetek <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "personitem.h" #include "contactitem.h" #include <Nepomuk2/Vocabulary/PIMO> #include <Nepomuk2/Vocabulary/NCO> #include <Nepomuk2/Resource> #include <Nepomuk2/Variant> #include <Soprano/Vocabulary/NAO> #include <KDebug> PersonItem::PersonItem(const QUrl &personUri) { setData(personUri, PersonsModel::UriRole); } PersonItem::PersonItem(const Nepomuk2::Resource &person) { setData(person.uri(), PersonsModel::UriRole); setContacts(person.property(Nepomuk2::Vocabulary::PIMO::groundingOccurrence()).toUrlList()); kDebug() << "new person" << text() << rowCount(); } QVariant PersonItem::queryChildrenForRole(int role) const { QVariant ret; for (int i = 0; i < rowCount(); i++) { QVariant value = child(i)->data(role); if (!value.isNull()) { ret = value; break; } } return ret; } QVariantList PersonItem::queryChildrenForRoleList(int role) const { QVariantList ret; for (int i = 0; i < rowCount(); i++) { QVariant value = child(i)->data(role); if (value.type() == QVariant::List) { ret += value.toList(); } else if (!value.isNull()) { ret += value; } } return ret; } QVariant PersonItem::data(int role) const { if (role == PersonsModel::PresenceTypeRole) { //TODO: return most online presence } QVariantList ret; for (int i = 0; i < rowCount(); i++) { QVariant value = child(i)->data(role); //these roles must return single QVariant if ((role == Qt::DisplayRole || role == Qt::DecorationRole || role == PersonsModel::UriRole) && !value.isNull()) { return value; } if (value.type() == QVariant::List) { ret += value.toList(); } else if (!value.isNull()) { ret += value; } } if (ret.isEmpty()) { //we need to return empty qvariant here, otherwise we'd get a qvariant //with empty qvariantlist, which would get parsed as non-empty qvariant return QVariant(); } return ret; } void PersonItem::removeContacts(const QList<QUrl> &contacts) { kDebug() << "remove contacts" << contacts; for (int i = 0; i < rowCount(); ) { QStandardItem *item = child(i); if (item && contacts.contains(item->data(PersonsModel::UriRole).toUrl())) { model()->invisibleRootItem()->appendRow(takeRow(i)); } else { ++i; } } emitDataChanged(); } void PersonItem::addContacts(const QList<QUrl> &_contacts) { QList<QUrl> contacts(_contacts); //get existing child-contacts and remove them from the new ones QVariantList uris = queryChildrenForRoleList(PersonsModel::UriRole); foreach (const QVariant &uri, uris) { contacts.removeOne(uri.toUrl()); } //query the model for the contacts, if they are present, then need to be just moved QList<QStandardItem*> toplevelContacts; foreach (const QUrl &uri, contacts) { QModelIndex contactIndex = qobject_cast<PersonsModel*>(model())->indexForUri(uri); if (contactIndex.isValid()) { toplevelContacts.append(qobject_cast<PersonsModel*>(model())->takeRow(contactIndex.row())); } } //append the moved contacts to this person and remove them from 'contacts' //so they are not added twice foreach (QStandardItem *contactItem, toplevelContacts) { //FIXME: we need to remove the fake person item here ContactItem *contact = dynamic_cast<ContactItem*>(contactItem); appendRow(contact); contacts.removeOne(contact->uri()); } QList<ContactItem*> rows; foreach (const QUrl &uri, contacts) { ContactItem *item = new ContactItem(uri); item->loadData(); appendRow(item); } emitDataChanged(); } void PersonItem::setContacts(const QList<QUrl> &contacts) { kDebug() << "set contacts" << contacts; if (contacts.isEmpty()) { //nothing to do here return; } if (hasChildren()) { QList<QUrl> toRemove; QVariantList uris = queryChildrenForRoleList(PersonsModel::UriRole); foreach (const QVariant &contact, uris) { if (!contacts.contains(contact.toUrl())) toRemove += contact.toUrl(); } removeContacts(toRemove); } QList<QUrl> toAdd; foreach (const QUrl &contact, contacts) { toAdd += contact; } addContacts(toAdd); Q_ASSERT(hasChildren()); } <|endoftext|>
<commit_before> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <unistd.h> #include "au/string.h" // au::str() #include "au/Cronometer.h" // au::Cronometer #include "au/CommandLine.h" // au::CommandLine class Position { public: double x; double y; Position() { x = 0; y = 0; } Position( double _x , double _y ) { x = _x; y = _y; } void set( double _x , double _y ) { x = _x; y = _y; } void set_in_limits( ) { set_in_limits(&x); set_in_limits(&y); } private: void set_in_limits( double* var ) { if( *var < 0) *var = 0; if( *var > 1000 ) *var = 1000; } }; Position getHome( size_t user ) { return Position( 10 * ( user%100 ) , 1000 - 10 * ( user%100 ) ); } Position getWork( size_t user ) { return Position( 1000 - 10 * ( user%100 ) , 10 * ( user%100 ) ); } int period; Position getPosition( size_t user ) { if( time(NULL)%period < (period/2) ) return getHome(user); else return getWork(user); return Position( rand()%1000 , rand()%1000 ); } int main( int args , const char*argv[] ) { // Random sequence generated srand( time(NULL)); au::CommandLine cmd; cmd.set_flag_uint64("users", 40000000 ); // Number of users cmd.set_flag_uint64("rate", 10000 ); // Number of CDRS per second cmd.set_flag_uint64("period", 300 ); // Period of work-home in seconds cmd.set_flag_boolean("h"); cmd.set_flag_boolean("help"); cmd.set_flag_boolean("commands"); cmd.parse( args, argv ); period = cmd.get_flag_uint64("period"); if( cmd.get_flag_bool("h") || cmd.get_flag_bool("help") ) { printf("\n"); printf(" ------------------------------------------------- \n"); printf(" Help %s\n" , argv[0] ); printf(" ------------------------------------------------- \n"); printf(" Simple command line tool to generate fake data for simple_mobility demo\n\n"); printf(" %s -commands Generates the command to setup home/work areas\n", argv[0] ); printf(" %s Generates the CDRS \n", argv[0] ); printf("\n"); printf(" Option: -users X Change the number of users ( default 20000000 ) \n" ); printf(" Option: -rate X Change number of CDRS per second ( default 10000 ) \n" ); printf(" Option: -period X Change period work-home in seconds (default 300 secs )\n"); printf("\n"); return 0; } size_t num_users = cmd.get_flag_uint64("users"); size_t rate = cmd.get_flag_uint64("rate"); fprintf(stderr,"%s: Setup %lu users and %lu cdrs/second\n" , argv[0] , num_users , rate ); size_t total_num = 0; size_t total_size = 0; if( cmd.get_flag_bool("commands") ) { for ( size_t i = 0 ; i < num_users ; i++ ) { Position home = getHome(i); Position work = getWork(i); printf("%lu AREA_CREATE home %f %f 200 \n" , i , home.x , home.y ); printf("%lu AREA_CREATE work %f %f 200 \n" , i , work.x , work.y ); } fprintf(stderr,"%s: Generated %lu messages" , argv[0] , num_users ); return 0; } au::Cronometer cronometer; size_t theoretical_seconds = 0; while( true ) { // Generate messages for the next second.... theoretical_seconds += 1; for ( size_t i = 0 ; i < rate ; i++ ) { size_t user = rand()%num_users; Position p = getPosition( user ); total_size += printf("%lu CDR %f %f %lu\n", user , p.x , p.y , time(NULL) ); total_num++; } size_t total_seconds = cronometer.diffTimeInSeconds(); if( total_seconds < theoretical_seconds ) { int seconds_to_sleep = (int) theoretical_seconds - total_seconds; fprintf(stderr,"%s: Sleeping %d seconds to keep rate %s\n", argv[0] , seconds_to_sleep , au::str( rate , "Events/sec" ).c_str() ); sleep( seconds_to_sleep ); } if( (theoretical_seconds%10) == 0) { fprintf(stderr,"%s: Generated %s lines ( %s bytes ) in %s. Rate: %s / %s.\n" , argv[0] , au::str(total_num).c_str() , au::str(total_size).c_str(), au::time_string( total_seconds ).c_str() , au::str( (double)total_num/(double)total_seconds ,"Lines/s" ).c_str() , au::str( (double)total_size/(double)total_seconds,"Bps").c_str() ); } } } <commit_msg>More flexibe simple_mobility_generator for the demo<commit_after> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <unistd.h> #include "au/string.h" // au::str() #include "au/Cronometer.h" // au::Cronometer #include "au/CommandLine.h" // au::CommandLine class Position { public: double x; double y; Position() { x = 0; y = 0; } Position( double _x , double _y ) { x = _x; y = _y; } void set( double _x , double _y ) { x = _x; y = _y; } void set_in_limits( ) { set_in_limits(&x); set_in_limits(&y); } private: void set_in_limits( double* var ) { if( *var < 0) *var = 0; if( *var > 1000 ) *var = 1000; } }; Position getHome( size_t user ) { return Position( 10 * ( user%100 ) , 1000 - 10 * ( user%100 ) ); } Position getWork( size_t user ) { return Position( 1000 - 10 * ( user%100 ) , 10 * ( user%100 ) ); } int period; Position getPosition( size_t user ) { if( time(NULL)%period < (period/2) ) return getHome(user); else return getWork(user); return Position( rand()%1000 , rand()%1000 ); } size_t num_users; size_t current_user; bool progresive; size_t getUser() { if ( progresive ) { current_user++; if( current_user >= num_users ) current_user=0; return current_user; } return rand()%num_users; } int main( int args , const char*argv[] ) { // Random sequence generated srand( time(NULL)); au::CommandLine cmd; cmd.set_flag_uint64("users", 40000000 ); // Number of users cmd.set_flag_uint64("rate", 10000 ); // Number of CDRS per second cmd.set_flag_uint64("period", 300 ); // Period of work-home in seconds cmd.set_flag_boolean("h"); cmd.set_flag_boolean("help"); cmd.set_flag_boolean("commands"); cmd.set_flag_boolean("progressive"); cmd.parse( args, argv ); period = cmd.get_flag_uint64("period"); progresive = cmd.get_flag_bool("progressive"); num_users = cmd.get_flag_uint64("users"); current_user = 0; if( cmd.get_flag_bool("h") || cmd.get_flag_bool("help") ) { printf("\n"); printf(" ------------------------------------------------- \n"); printf(" Help %s\n" , argv[0] ); printf(" ------------------------------------------------- \n"); printf(" Simple command line tool to generate fake data for simple_mobility demo\n\n"); printf(" %s -commands Generates the command to setup home/work areas\n", argv[0] ); printf(" %s Generates the CDRS \n", argv[0] ); printf("\n"); printf(" Option: -users X Change the number of users ( default 20000000 ) \n" ); printf(" Option: -rate X Change number of CDRS per second ( default 10000 ) \n" ); printf(" Option: -period X Change period work-home in seconds (default 300 secs )\n"); printf(" Option: -progressive Non random sequence of messages\n"; printf("\n"); return 0; } size_t rate = cmd.get_flag_uint64("rate"); fprintf(stderr,"%s: Setup %lu users and %lu cdrs/second\n" , argv[0] , num_users , rate ); size_t total_num = 0; size_t total_size = 0; if( cmd.get_flag_bool("commands") ) { for ( size_t i = 0 ; i < num_users ; i++ ) { Position home = getHome(i); Position work = getWork(i); printf("%lu AREA_CREATE home %f %f 200 \n" , i , home.x , home.y ); printf("%lu AREA_CREATE work %f %f 200 \n" , i , work.x , work.y ); } fprintf(stderr,"%s: Generated %lu messages" , argv[0] , num_users ); return 0; } au::Cronometer cronometer; size_t theoretical_seconds = 0; while( true ) { // Generate messages for the next second.... theoretical_seconds += 1; for ( size_t i = 0 ; i < rate ; i++ ) { size_t user = getUser(); Position p = getPosition( user ); total_size += printf("%lu CDR %f %f %lu\n", user , p.x , p.y , time(NULL) ); total_num++; } size_t total_seconds = cronometer.diffTimeInSeconds(); if( total_seconds < theoretical_seconds ) { int seconds_to_sleep = (int) theoretical_seconds - total_seconds; fprintf(stderr,"%s: Sleeping %d seconds to keep rate %s\n", argv[0] , seconds_to_sleep , au::str( rate , "Events/sec" ).c_str() ); sleep( seconds_to_sleep ); } if( (theoretical_seconds%10) == 0) { fprintf(stderr,"%s: Generated %s lines ( %s bytes ) in %s. Rate: %s / %s.\n" , argv[0] , au::str(total_num).c_str() , au::str(total_size).c_str(), au::time_string( total_seconds ).c_str() , au::str( (double)total_num/(double)total_seconds ,"Lines/s" ).c_str() , au::str( (double)total_size/(double)total_seconds,"Bps").c_str() ); } } } <|endoftext|>
<commit_before>#include <algorithm> #include <string> #include <vector> #include <boost/optional.hpp> #include <locale> #include "../../../src/prompt.hh" #include "../../../src/configuration.hh" #include "../../../src/to_str.hh" #include "../../../src/show_message.hh" #include "../../../src/visual.hh" #include "move.hh" void mvline(contents& contents, boost::optional<int> line) { if(line) { contents.x = 0; int cont = line.get(); if(cont < 0) { show_message("Can't move to a negative line!"); contents.y = 0; return; } contents.y = cont; if(cont >= contents.cont.size()) { contents.y = contents.cont.size() - 1; show_message("Can't move past end of buffer!"); } } else { while(true) { std::string str = prompt("Goto line: "); try { int res = std::stoi(str); mvline(contents, res); return; } catch(std::invalid_argument) { continue; } } } } void mv(contents& contents, unsigned long _y, unsigned long _x) { contents.y = _y; contents.x = _x; if((long) contents.y < 0) contents.y = 0; if(contents.y >= contents.cont.size()) contents.y = contents.cont.size() - 1; if((long) contents.x < 0) contents.x = 0; if(contents.x >= contents.cont[contents.y].size()) contents.x = contents.cont[contents.y].size() - 1; } void mvrel(contents& contents, long y, long x) { if(y < 0) mvu(contents,-y); else mvd(contents, y); if(x < 0) mvb(contents,-x); else mvf(contents, x); } void mvcol(contents& contents, boost::optional<int> col) { if(col) { unsigned int len = contents.cont[contents.y].length(); if(len >= col.get()) { contents.x = col.get(); contents.waiting_for_desired = false; } else { show_message((std::string("Can't move to column: ") + int_to_str(col.get())).c_str()); } } else { while(true) { std::string str = prompt("Goto column: "); try { int res = std::stoi(str); mvcol(contents, res); return; } catch(std::invalid_argument) { continue; } } } } void mvsot(contents& contents, boost::optional<int> op) { mvsol(contents, op); const std::string& str = contents.cont[contents.y]; for(unsigned int i = 0; i < str.length(); i++) { if(str[i] == ' ' || str[i] == '\t') mvf(contents, op); else break; } } void mveol(contents& contents, boost::optional<int>) { mvcol(contents,contents.cont[contents.y].length() - 1); } void mvsol(contents& contents, boost::optional<int>) { mvcol(contents,0); } void mvsop(contents& contents, boost::optional<int>) { contents.y = 0; contents.x = 0; contents.waiting_for_desired = false; } void mveop(contents& contents, boost::optional<int>) { contents.y = contents.cont.size() - 1; contents.x = 0; contents.waiting_for_desired = false; } void mvd(contents& contents, boost::optional<int> op) { int times = op ? op.get() : 1; if(contents.y + times < 0 || contents.y + times >= contents.cont.size()) { show_message("Can't move to that location (start/end of buffer)"); return; } int vis = to_visual(contents.cont[contents.y],contents.x); contents.y += times; unsigned int len = contents.cont[contents.y].length(); if(contents.waiting_for_desired) { if((int)contents.x < 0) { contents.x = len - 1; unsigned int vis = from_visual(contents.cont[contents.y], contents.desired_x); if(vis < contents.x) { contents.x = vis; contents.waiting_for_desired = false; } } else if(contents.x >= len) { contents.x = len - 1; } else if((contents.desired_x > contents.x && contents.desired_x < len) || contents.desired_x == 0) { // x desired len contents.x = contents.desired_x; contents.waiting_for_desired = false; } else { // x len desired contents.x = len - 1; } } else if(len <= contents.x && len > 0) { contents.waiting_for_desired = true; contents.desired_x = contents.x; contents.x = len - 1; } else { int des = contents.x; contents.x = from_visual(contents.cont[contents.y],vis); if(len == 0) { contents.waiting_for_desired = true; contents.desired_x = des; } } contents.x = (long) contents.x >= 0 ? contents.x : 0; } void mvu(contents& contents, boost::optional<int> op) { if(op) mvd(contents,-op.get()); else mvd(contents,-1); } inline static bool isDeliminator(char ch) { return std::find(DELIMINATORS.begin(), DELIMINATORS.end(), ch) != DELIMINATORS.end(); } inline static bool isWhitespace(char ch) { static const std::locale loc; return std::isspace(ch, loc); } void mvfw(contents& contents, boost::optional<int> op) { if(op && op.get() < 0) return mvbw(contents, op.get() * -1); int num = op ? op.get() : 1; if(num == 0 || num == -0) return; if(num < 0) return mvbw(contents, -op.get()); //if deliminator then move forward until not deliminator then move over whitespace //else move foward until (whitespace -> move till not whitespace) or (deliminator -> stop) #define boundsCheck if(contents.y >= contents.cont.size() || \ (contents.y == contents.cont.size() - 1 && \ contents.x >= contents.cont[contents.y].size())) return; #define ch contents.cont[contents.y][contents.x] if(isDeliminator(ch)) { do { mvf(contents); boundsCheck; } while(isDeliminator(ch)); while(isWhitespace(ch)) { mvf(contents); boundsCheck; } } else { while(!isDeliminator(ch) and !isWhitespace(ch)) { mvf(contents); boundsCheck; } if(isWhitespace(ch)) { while(isWhitespace(ch)) { mvf(contents); boundsCheck; } } else { while(isDeliminator(ch)) { mvf(contents); boundsCheck; } } } #undef boundsCheck #undef ch if(num > 0) mvfw(contents,num - 1); } void mvfeow(contents& contents, boost::optional<int> op) { //move at least one forward //move over non deliminators //move over deliminators } void mvbw(contents& contents, boost::optional<int> op) { //move back one then //if delimitor then move back until no delimitor //else if whitespace then move back until not whitespace then // move back consistently over delimitors or word chars //else /*word char*/ move back until not word char or // whitespace //move forward one } inline static unsigned int fixLen(unsigned int len) { return len ? len : 1; } void mvf(contents& contents, boost::optional<int> op) { int times = op ? op.get() : 1; long newx = contents.x + times; try { while(fixLen(contents.cont.at(contents.y).length()) <= newx) { newx -= fixLen(contents.cont[contents.y].length()); contents.y++; } } catch(...) { } if(contents.y >= contents.cont.size()) contents.y = contents.cont.size() - 1; if(contents.x < 0) contents.x = 0; else contents.x = newx; contents.waiting_for_desired = false; } void mvb(contents& contents, boost::optional<int> op) { int times = op ? op.get() : 1; if(contents.y == 0 && contents.x == 0) return; long newx = contents.x - times; try { while(newx < 0) { contents.y--; newx += fixLen(contents.cont.at(contents.y).length()); } } catch(...) { } if(newx < 0) contents.x = 0; else contents.x = newx; contents.waiting_for_desired = false; } <commit_msg>Implement ``mvfeow``, ``mvbw``, and fix ``mvfw``<commit_after>#include <algorithm> #include <string> #include <vector> #include <boost/optional.hpp> #include <locale> #include "../../../src/prompt.hh" #include "../../../src/configuration.hh" #include "../../../src/to_str.hh" #include "../../../src/show_message.hh" #include "../../../src/visual.hh" #include "move.hh" void mvline(contents& contents, boost::optional<int> line) { if(line) { contents.x = 0; int cont = line.get(); if(cont < 0) { show_message("Can't move to a negative line!"); contents.y = 0; return; } contents.y = cont; if(cont >= contents.cont.size()) { contents.y = contents.cont.size() - 1; show_message("Can't move past end of buffer!"); } } else { while(true) { std::string str = prompt("Goto line: "); try { int res = std::stoi(str); mvline(contents, res); return; } catch(std::invalid_argument) { continue; } } } } void mv(contents& contents, unsigned long _y, unsigned long _x) { contents.y = _y; contents.x = _x; if((long) contents.y < 0) contents.y = 0; if(contents.y >= contents.cont.size()) contents.y = contents.cont.size() - 1; if((long) contents.x < 0) contents.x = 0; if(contents.x >= contents.cont[contents.y].size()) contents.x = contents.cont[contents.y].size() - 1; } void mvrel(contents& contents, long y, long x) { if(y < 0) mvu(contents,-y); else mvd(contents, y); if(x < 0) mvb(contents,-x); else mvf(contents, x); } void mvcol(contents& contents, boost::optional<int> col) { if(col) { unsigned int len = contents.cont[contents.y].length(); if(len >= col.get()) { contents.x = col.get(); contents.waiting_for_desired = false; } else { show_message((std::string("Can't move to column: ") + int_to_str(col.get())).c_str()); } } else { while(true) { std::string str = prompt("Goto column: "); try { int res = std::stoi(str); mvcol(contents, res); return; } catch(std::invalid_argument) { continue; } } } } void mvsot(contents& contents, boost::optional<int> op) { mvsol(contents, op); const std::string& str = contents.cont[contents.y]; for(unsigned int i = 0; i < str.length(); i++) { if(str[i] == ' ' || str[i] == '\t') mvf(contents, op); else break; } } void mveol(contents& contents, boost::optional<int>) { mvcol(contents,contents.cont[contents.y].length() - 1); } void mvsol(contents& contents, boost::optional<int>) { mvcol(contents,0); } void mvsop(contents& contents, boost::optional<int>) { contents.y = 0; contents.x = 0; contents.waiting_for_desired = false; } void mveop(contents& contents, boost::optional<int>) { contents.y = contents.cont.size() - 1; contents.x = 0; contents.waiting_for_desired = false; } void mvd(contents& contents, boost::optional<int> op) { int times = op ? op.get() : 1; if(contents.y + times < 0 || contents.y + times >= contents.cont.size()) { show_message("Can't move to that location (start/end of buffer)"); return; } int vis = to_visual(contents.cont[contents.y],contents.x); contents.y += times; unsigned int len = contents.cont[contents.y].length(); if(contents.waiting_for_desired) { if((int)contents.x < 0) { contents.x = len - 1; unsigned int vis = from_visual(contents.cont[contents.y], contents.desired_x); if(vis < contents.x) { contents.x = vis; contents.waiting_for_desired = false; } } else if(contents.x >= len) { contents.x = len - 1; } else if((contents.desired_x > contents.x && contents.desired_x < len) || contents.desired_x == 0) { // x desired len contents.x = contents.desired_x; contents.waiting_for_desired = false; } else { // x len desired contents.x = len - 1; } } else if(len <= contents.x && len > 0) { contents.waiting_for_desired = true; contents.desired_x = contents.x; contents.x = len - 1; } else { int des = contents.x; contents.x = from_visual(contents.cont[contents.y],vis); if(len == 0) { contents.waiting_for_desired = true; contents.desired_x = des; } } contents.x = (long) contents.x >= 0 ? contents.x : 0; } void mvu(contents& contents, boost::optional<int> op) { if(op) mvd(contents,-op.get()); else mvd(contents,-1); } inline static bool isDeliminator(char ch) { return std::find(DELIMINATORS.begin(), DELIMINATORS.end(), ch) != DELIMINATORS.end(); } inline static bool isWhitespace(char ch) { static const std::locale loc; return std::isspace(ch, loc); } void mvfw(contents& contents, boost::optional<int> op) { if(op && op.get() < 0) return mvbw(contents, op.get() * -1); int num = op ? op.get() : 1; if(num == 0 || num == -0) return; //if whitespace move forward until not whitespace //else if deliminator then move forward until not deliminator then move over whitespace //else move foward until deliminator or whitespace #define boundsCheck if(contents.y >= contents.cont.size() \ || (contents.y == contents.cont.size() - 1 && \ contents.x >= contents.cont[contents.y].size()) \ || (contents.x == 0 && !isWhitespace(ch))) return; #define ch contents.cont[contents.y][contents.x] if(isWhitespace(ch)) { do { mvf(contents); boundsCheck; } while(isWhitespace(ch)); } else if(isDeliminator(ch)) { do { mvf(contents); boundsCheck; } while(isDeliminator(ch)); while(isWhitespace(ch)) { mvf(contents); boundsCheck; } } else { do { mvf(contents); boundsCheck; } while(!isDeliminator(ch) && !isWhitespace(ch)); while(isWhitespace(ch)) { mvf(contents); boundsCheck; } } if(num > 1) mvfw(contents,num - 1); #undef boundsCheck } void mvfeow(contents& contents, boost::optional<int> op) { if(op && op.get() < 0) return mvbw(contents, op.get() * -1); int num = op ? op.get() : 1; if(num == 0 || num == -0) return; //move at least one forward //move over whitespace //if delimitor then move until not delimitor //else move until delimitor or whitespace //move back one #define boundsCheck if(contents.y >= contents.cont.size() \ || (contents.y == contents.cont.size() - 1 && \ contents.x >= contents.cont[contents.y].size()) \ || (contents.x == 0 && !isWhitespace(ch))) { \ mvb(contents); \ return; \ } mvf(contents); while(isWhitespace(ch)) { mvf(contents); boundsCheck; } if(isDeliminator(ch)) { do { mvf(contents); boundsCheck; } while(isDeliminator(ch)); mvb(contents); } else { do { mvf(contents); boundsCheck; } while(!isDeliminator(ch) && !isWhitespace(ch)); mvb(contents); } if(num > 1) mvfeow(contents,num - 1); #undef boundsCheck } void mvbw(contents& contents, boost::optional<int> op) { if(op && op.get() < 0) return mvfw(contents, op.get() * -1); int num = op ? op.get() : 1; if(num == 0 || num == -0) return; //move back one then //if delimitor then move back until no delimitor //else if whitespace then move back until not whitespace then // move back consistently over delimitors or word chars //else /*word char*/ move back until not word char or // whitespace //move forward one #define boundsCheck if(contents.y < 0 \ || (contents.y == 0 && contents.x == 0) \ || (contents.x == 0 && !isWhitespace(ch))) return; mvb(contents); while(isWhitespace(ch)) { mvb(contents); boundsCheck; } if(isDeliminator(ch)) { do { mvb(contents); boundsCheck; } while(isDeliminator(ch)); mvf(contents); } else { do { mvb(contents); boundsCheck; } while(!isDeliminator(ch) && !isWhitespace(ch)); mvf(contents); } if(num > 1) mvbw(contents,num - 1); #undef boundsCheck #undef ch } inline static unsigned int fixLen(unsigned int len) { return len ? len : 1; } void mvf(contents& contents, boost::optional<int> op) { int times = op ? op.get() : 1; long newx = contents.x + times; try { while(fixLen(contents.cont.at(contents.y).length()) <= newx) { newx -= fixLen(contents.cont[contents.y].length()); contents.y++; } } catch(...) { } if(contents.y >= contents.cont.size()) contents.y = contents.cont.size() - 1; if(contents.x < 0) contents.x = 0; else contents.x = newx; contents.waiting_for_desired = false; } void mvb(contents& contents, boost::optional<int> op) { int times = op ? op.get() : 1; if(contents.y == 0 && contents.x == 0) return; long newx = contents.x - times; try { while(newx < 0) { contents.y--; newx += fixLen(contents.cont.at(contents.y).length()); } } catch(...) { } if(newx < 0) contents.x = 0; else contents.x = newx; contents.waiting_for_desired = false; } <|endoftext|>
<commit_before>#include <omp.h> #include "configure.h" // This code is from BVLC/Caffe changed a little bit : link https://github.com/BVLC/caffe/blob/master/src/caffe/util/im2col.cpp // Function uses casting from int to unsigned to compare if value of // parameter a is greater or equal to zero and lower than value of // parameter b. The b parameter is of type signed and is always positive, // therefore its value is always lower than 0x800... where casting // negative value of a parameter converts it to value higher than 0x800... // The casting allows to use one condition instead of two. inline bool is_a_ge_zero_and_a_lt_b(int a, int b) { return static_cast<unsigned>(a) < static_cast<unsigned>(b); } #define H_BL 32 #define H_NB_BL N/H_BL #define W_BL 32 #define W_NB_BL N/W_BL void im2col_cpu(const float* data_im, const int channels, const int height, const int width, const int kernel_h, const int kernel_w, const int pad_h, const int pad_w, float* data_col) { int height_col = (height - kernel_h) + 1; int width_col = (width - kernel_w) + 1; int channels_col = channels * kernel_h * kernel_w; omp_set_num_threads(4); #pragma omp parallel for for( int h_b = 0; h_b < H_NB_BL; h_b++){ int h_start = h_b * H_BL; int h_end = std::min((h_b + 1) * H_BL, N); for( int w_b = 0; w_b < W_NB_BL; w_b++){ int w_start = w_b * W_BL; int w_end = std::min((w_b + 1) * W_BL, N); for (int c = 0; c < channels_col; ++c) { int w_offset = c % kernel_w; int h_offset = (c / kernel_w) % kernel_h; int c_im = c / kernel_h / kernel_w; const int hc0 = h_offset; const int wc0 = w_offset; for (int h = h_start; h < h_end; ++h) { int h_pad = h + hc0; const int row_offset = (c * height_col + h) * width_col; float* data_col_off = data_col + row_offset; if ((((unsigned)h_pad) < ((unsigned)height)) ){ const int srow_offset = (c_im * height + h_pad) * width; float * data_im_offset = (float*)data_im + srow_offset; for (int w = w_start; w < w_end; ++w) { int w_pad = w + wc0; data_col_off[w] = data_im_offset[w_pad]; if (((unsigned)w_pad) >= ((unsigned)width)) data_col_off[w] = (float)0; } } else for (int w = w_start; w < w_end; ++w) data_col[row_offset + w] = (float)0; } } } } } <commit_msg>Fix formatting<commit_after>#include <omp.h> #include "configure.h" // This code is from BVLC/Caffe changed a little bit : link https://github.com/BVLC/caffe/blob/master/src/caffe/util/im2col.cpp // Function uses casting from int to unsigned to compare if value of // parameter a is greater or equal to zero and lower than value of // parameter b. The b parameter is of type signed and is always positive, // therefore its value is always lower than 0x800... where casting // negative value of a parameter converts it to value higher than 0x800... // The casting allows to use one condition instead of two. inline bool is_a_ge_zero_and_a_lt_b(int a, int b) { return static_cast<unsigned>(a) < static_cast<unsigned>(b); } #define H_BL 32 #define H_NB_BL N/H_BL #define W_BL 32 #define W_NB_BL N/W_BL void im2col_cpu(const float* data_im, const int channels, const int height, const int width, const int kernel_h, const int kernel_w, const int pad_h, const int pad_w, float* data_col) { int height_col = (height - kernel_h) + 1; int width_col = (width - kernel_w) + 1; int channels_col = channels * kernel_h * kernel_w; omp_set_num_threads(4); #pragma omp parallel for for( int h_b = 0; h_b < H_NB_BL; h_b++){ int h_start = h_b * H_BL; int h_end = std::min((h_b + 1) * H_BL, N); for( int w_b = 0; w_b < W_NB_BL; w_b++){ int w_start = w_b * W_BL; int w_end = std::min((w_b + 1) * W_BL, N); for (int c = 0; c < channels_col; ++c) { int w_offset = c % kernel_w; int h_offset = (c / kernel_w) % kernel_h; int c_im = c / kernel_h / kernel_w; const int hc0 = h_offset; const int wc0 = w_offset; for (int h = h_start; h < h_end; ++h) { int h_pad = h + hc0; const int row_offset = (c * height_col + h) * width_col; float* data_col_off = data_col + row_offset; if ((((unsigned)h_pad) < ((unsigned)height)) ){ const int srow_offset = (c_im * height + h_pad) * width; float * data_im_offset = (float*)data_im + srow_offset; for (int w = w_start; w < w_end; ++w) { int w_pad = w + wc0; data_col_off[w] = data_im_offset[w_pad]; if (((unsigned)w_pad) >= ((unsigned)width)) data_col_off[w] = (float)0; } } else for (int w = w_start; w < w_end; ++w) data_col[row_offset + w] = (float)0; } } } } } <|endoftext|>
<commit_before>/* Copyright (c) 2008-2010, Avian Contributors Permission to use, copy, modify, and/or 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. There is NO WARRANTY for this software. See license.txt for details. */ #include "machine.h" #include "heapwalk.h" using namespace vm; namespace { namespace local { enum { Root, Size, ClassName, Push, Pop }; void write1(FILE* out, uint8_t v) { size_t n UNUSED = fwrite(&v, 1, 1, out); } void write4(FILE* out, uint32_t v) { uint8_t b[] = { v >> 24, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF }; size_t n UNUSED = fwrite(b, 4, 1, out); } void writeString(FILE* out, int8_t* p, unsigned size) { write4(out, size); size_t n UNUSED = fwrite(p, size, 1, out); } unsigned objectSize(Thread* t, object o) { return extendedSize(t, o, baseSize(t, o, objectClass(t, o))); } } // namespace local } // namespace namespace vm { void dumpHeap(Thread* t, FILE* out) { class Visitor: public HeapVisitor { public: Visitor(Thread* t, FILE* out): t(t), out(out), nextNumber(1) { } virtual void root() { write1(out, local::Root); } virtual unsigned visitNew(object p) { if (p) { unsigned number = nextNumber++; local::write4(out, number); local::write1(out, local::Size); local::write4(out, local::objectSize(t, p)); if (objectClass(t, p) == type(t, Machine::ClassType)) { object name = className(t, p); if (name) { local::write1(out, local::ClassName); local::writeString(out, &byteArrayBody(t, name, 0), byteArrayLength(t, name) - 1); } } return number; } else { return 0; } } virtual void visitOld(object, unsigned number) { local::write4(out, number); } virtual void push(object, unsigned, unsigned) { local::write1(out, local::Push); } virtual void pop() { local::write1(out, local::Pop); } Thread* t; FILE* out; unsigned nextNumber; } visitor(t, out); HeapWalker* w = makeHeapWalker(t, &visitor); w->visitAllRoots(); w->dispose(); } } // namespace vm <commit_msg>fix C++11 errors in heapdump.cpp<commit_after>/* Copyright (c) 2008-2010, Avian Contributors Permission to use, copy, modify, and/or 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. There is NO WARRANTY for this software. See license.txt for details. */ #include "machine.h" #include "heapwalk.h" using namespace vm; namespace { namespace local { enum { Root, Size, ClassName, Push, Pop }; void write1(FILE* out, uint8_t v) { size_t n UNUSED = fwrite(&v, 1, 1, out); } void write4(FILE* out, uint32_t v) { uint8_t b[] = { static_cast<uint8_t>( v >> 24 ), static_cast<uint8_t>((v >> 16) & 0xFF), static_cast<uint8_t>((v >> 8) & 0xFF), static_cast<uint8_t>( v & 0xFF) }; size_t n UNUSED = fwrite(b, 4, 1, out); } void writeString(FILE* out, int8_t* p, unsigned size) { write4(out, size); size_t n UNUSED = fwrite(p, size, 1, out); } unsigned objectSize(Thread* t, object o) { return extendedSize(t, o, baseSize(t, o, objectClass(t, o))); } } // namespace local } // namespace namespace vm { void dumpHeap(Thread* t, FILE* out) { class Visitor: public HeapVisitor { public: Visitor(Thread* t, FILE* out): t(t), out(out), nextNumber(1) { } virtual void root() { write1(out, local::Root); } virtual unsigned visitNew(object p) { if (p) { unsigned number = nextNumber++; local::write4(out, number); local::write1(out, local::Size); local::write4(out, local::objectSize(t, p)); if (objectClass(t, p) == type(t, Machine::ClassType)) { object name = className(t, p); if (name) { local::write1(out, local::ClassName); local::writeString(out, &byteArrayBody(t, name, 0), byteArrayLength(t, name) - 1); } } return number; } else { return 0; } } virtual void visitOld(object, unsigned number) { local::write4(out, number); } virtual void push(object, unsigned, unsigned) { local::write1(out, local::Push); } virtual void pop() { local::write1(out, local::Pop); } Thread* t; FILE* out; unsigned nextNumber; } visitor(t, out); HeapWalker* w = makeHeapWalker(t, &visitor); w->visitAllRoots(); w->dispose(); } } // namespace vm <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ignoreMiddleDot_ja_JP.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-07 17:28:56 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // prevent internal compiler error with MSVC6SP3 #include <utility> #define TRANSLITERATION_MiddleDot_ja_JP #include <transliteration_Ignore.hxx> namespace com { namespace sun { namespace star { namespace i18n { sal_Unicode ignoreMiddleDot_ja_JP_translator (const sal_Unicode c) { switch (c) { case 0x30FB: // KATAKANA MIDDLE DOT case 0xFF65: // HALFWIDTH KATAKANA MIDDLE DOT // no break; return 0xffff; // Skip this character } return c; } ignoreMiddleDot_ja_JP::ignoreMiddleDot_ja_JP() { func = ignoreMiddleDot_ja_JP_translator; table = 0; map = 0; transliterationName = "ignoreMiddleDot_ja_JP"; implementationName = "com.sun.star.i18n.Transliteration.ignoreMiddleDot_ja_JP"; } } } } } <commit_msg>INTEGRATION: CWS pchfix02 (1.7.80); FILE MERGED 2006/09/01 17:30:51 kaib 1.7.80.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ignoreMiddleDot_ja_JP.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2006-09-17 09:27:05 $ * * 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_i18npool.hxx" // prevent internal compiler error with MSVC6SP3 #include <utility> #define TRANSLITERATION_MiddleDot_ja_JP #include <transliteration_Ignore.hxx> namespace com { namespace sun { namespace star { namespace i18n { sal_Unicode ignoreMiddleDot_ja_JP_translator (const sal_Unicode c) { switch (c) { case 0x30FB: // KATAKANA MIDDLE DOT case 0xFF65: // HALFWIDTH KATAKANA MIDDLE DOT // no break; return 0xffff; // Skip this character } return c; } ignoreMiddleDot_ja_JP::ignoreMiddleDot_ja_JP() { func = ignoreMiddleDot_ja_JP_translator; table = 0; map = 0; transliterationName = "ignoreMiddleDot_ja_JP"; implementationName = "com.sun.star.i18n.Transliteration.ignoreMiddleDot_ja_JP"; } } } } } <|endoftext|>
<commit_before>/* **** **** **** **** **** **** **** **** * * * _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * _/ _/ _/ _/ _/ _/ * _/ _/ _/ _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * * bit by bit * bbb/difference_sequence.hpp * * author: ISHII 2bit * mail: [email protected] * * **** **** **** **** **** **** **** **** */ #pragma once #include <bbb/core/tmp/traits.hpp> #include <bbb/core/tmp/type_container/type_sequence/type_sequence.hpp> namespace bbb { namespace type_sequence_operations { template <typename s, typename t> struct difference_sequence; template <typename s, typename t> using difference_sequence_t = get_type<difference_sequence<s, t>>; template <typename s, typename t, typename ... ts> struct difference_sequence<s, type_sequence<t, ts ...>> { using type = difference_sequence_t<remove_t<t, s>, type_sequence<ts ...>>; }; template <typename s> struct difference_sequence<s, type_sequence<>> { using type = s; }; #if BBB_EXEC_UNIT_TEST namespace difference_sequence_test { using test1 = unit_test::assert< difference_sequence_t<type_sequence<int, int, char>, type_sequence<int>>, type_sequence<int, char> >; }; #endif }; }; <commit_msg>WIP add comments<commit_after>/* **** **** **** **** **** **** **** **** * * * _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * _/ _/ _/ _/ _/ _/ * _/ _/ _/ _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * * bit by bit * bbb/difference_sequence.hpp * * author: ISHII 2bit * mail: [email protected] * * **** **** **** **** **** **** **** **** */ #pragma once #include <bbb/core/tmp/traits.hpp> #include <bbb/core/tmp/type_container/type_sequence/type_sequence.hpp> namespace bbb { namespace type_sequence_operations { /// @struct difference_sequence /// calculate difference of sequences /// @tparam s: type_sequence /// @tparam t: type_sequence /// s \ t /// ex. {a, b, b, c} \ {a, b, c} == {b} /// {a, b, c} \ {a, b, b, c} == {} /// {c, b, a} \ {a, b, c} == {} /// template <typename s, typename t> struct difference_sequence; /// @struct difference_sequence_t /// alias of get_type<diference_sequence<s, t>> template <typename s, typename t> using difference_sequence_t = get_type<difference_sequence<s, t>>; template <typename s, typename t, typename ... ts> struct difference_sequence<s, type_sequence<t, ts ...>> { using type = difference_sequence_t<remove_t<t, s>, type_sequence<ts ...>>; }; template <typename s> struct difference_sequence<s, type_sequence<>> { using type = s; }; #if BBB_EXEC_UNIT_TEST namespace difference_sequence_test { using test1 = unit_test::assert< difference_sequence_t<type_sequence<int, int, char>, type_sequence<int>>, type_sequence<int, char> >; }; #endif }; }; <|endoftext|>
<commit_before>/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "core/cross/precompile.h" #include "tests/common/win/testing_common.h" #include "core/cross/client.h" #include "core/cross/pack.h" #include "core/cross/renderer.h" #include "core/cross/bitmap.h" #include "core/cross/features.h" #include "core/cross/texture.h" #include "core/cross/render_surface.h" #include "core/cross/render_surface_set.h" #include "core/cross/renderer_platform.h" // Defined in testing_common.cc, for each platform. extern o3d::DisplayWindow* g_display_window; namespace o3d { class MockRenderer { public: explicit MockRenderer(Renderer* renderer) : renderer_(renderer) {} virtual ~MockRenderer() {} void StartRendering() { renderer_->set_rendering(true); } void FinishRendering() { renderer_->set_rendering(false); } void SetRenderSurfaces(const RenderSurface* surface, const RenderDepthStencilSurface* depth_surface) { renderer_->SetRenderSurfaces(surface, depth_surface); } void GetRenderSurfaces(const RenderSurface** surface, const RenderDepthStencilSurface** depth_surface) { renderer_->GetRenderSurfaces(surface, depth_surface); } private: Renderer* renderer_; }; class RenderSurfaceTest : public testing::Test { public: RenderSurfaceTest() : object_manager_(g_service_locator) {} ServiceLocator* service_locator() { return service_locator_; } MockRenderer* renderer() { return renderer_; } protected: virtual void SetUp() { service_locator_ = new ServiceLocator; features_ = new Features(service_locator_); pack_ = object_manager_->CreatePack(); renderer_ = new MockRenderer(g_renderer); renderer_->StartRendering(); } virtual void TearDown() { renderer_->FinishRendering(); pack_->Destroy(); delete features_; delete service_locator_; delete renderer_; } Pack* pack() { return pack_; } ServiceDependency<ObjectManager> object_manager_; ServiceLocator* service_locator_; Features* features_; Pack* pack_; MockRenderer* renderer_; }; // Test that non PoT textures can't make render surfaces TEST_F(RenderSurfaceTest, NonPowerOfTwoRenderSurfaceEnabled) { Texture2D* texture = pack()->CreateTexture2D(20, 32, Texture::ARGB8, 2, true); ASSERT_TRUE(NULL == texture); } // Test that a render surface can be created TEST_F(RenderSurfaceTest, CreateRenderSurfaceFromTexture2D) { Texture2D* texture = pack()->CreateTexture2D(16, 32, Texture::ARGB8, 2, true); ASSERT_TRUE(NULL != texture); RenderSurface::Ref render_surface = texture->GetRenderSurface(0); ASSERT_TRUE(NULL != render_surface); ASSERT_TRUE(NULL != render_surface->texture()); ASSERT_EQ(render_surface->width(), 16); ASSERT_EQ(render_surface->height(), 32); } TEST_F(RenderSurfaceTest, CreateRenderSurfaceFromTextureCUBE) { TextureCUBE* texture = pack()->CreateTextureCUBE(16, Texture::ARGB8, 2, true); ASSERT_TRUE(NULL != texture); RenderSurface::Ref render_surface = texture->GetRenderSurface( TextureCUBE::CubeFace::FACE_POSITIVE_X, 0); ASSERT_TRUE(NULL != render_surface); ASSERT_TRUE(NULL != render_surface->texture()); ASSERT_EQ(render_surface->width(), 16); ASSERT_EQ(render_surface->height(), 16); } TEST_F(RenderSurfaceTest, SwapRenderSurfaces) { Texture2D* texture = pack()->CreateTexture2D(16, 32, Texture::ARGB8, 2, true); ASSERT_TRUE(NULL != texture); RenderSurface::Ref render_surface = texture->GetRenderSurface(0); ASSERT_TRUE(NULL != render_surface); ASSERT_TRUE(texture == render_surface->texture()); RenderDepthStencilSurface* depth_surface = pack()->CreateDepthStencilSurface(16, 32); // Now swap surfaces. renderer()->SetRenderSurfaces(render_surface, depth_surface); const RenderSurface* test_render_surface = NULL; const RenderDepthStencilSurface* test_depth_surface = NULL; renderer()->GetRenderSurfaces(&test_render_surface, &test_depth_surface); ASSERT_TRUE(test_render_surface == render_surface); ASSERT_TRUE(test_depth_surface == depth_surface); } TEST_F(RenderSurfaceTest, SetBackSurfaces) { Texture2D* texture = pack()->CreateTexture2D(16, 32, Texture::ARGB8, 2, true); ASSERT_TRUE(NULL != texture); RenderSurface::Ref render_surface = texture->GetRenderSurface(0); ASSERT_TRUE(NULL != render_surface); ASSERT_TRUE(texture == render_surface->texture()); RenderDepthStencilSurface* depth_surface = pack()->CreateDepthStencilSurface(16, 32); // Save the original surfaces for comparison. const RenderSurface* original_render_surface = NULL; const RenderDepthStencilSurface* original_depth_surface = NULL; renderer()->GetRenderSurfaces(&original_render_surface, &original_depth_surface); // Now swap surfaces. renderer()->SetRenderSurfaces(render_surface, depth_surface); // Return the back buffers renderer()->SetRenderSurfaces(NULL, NULL); // Get the original surfaces again for comparison. const RenderSurface* restored_render_surface = NULL; const RenderDepthStencilSurface* restored_depth_surface = NULL; renderer()->GetRenderSurfaces(&original_render_surface, &original_depth_surface); ASSERT_TRUE(original_render_surface == restored_render_surface); ASSERT_TRUE(original_depth_surface == restored_depth_surface); } TEST_F(RenderSurfaceTest, RenderSurfaceSetTest) { Texture2D* texture = pack()->CreateTexture2D(16, 32, Texture::ARGB8, 2, true); ASSERT_TRUE(NULL != texture); RenderSurface::Ref render_surface = texture->GetRenderSurface(0); ASSERT_TRUE(NULL != render_surface); ASSERT_TRUE(texture == render_surface->texture()); RenderDepthStencilSurface* depth_surface = pack()->CreateDepthStencilSurface(16, 32); RenderSurfaceSet* render_surface_set = pack()->Create<RenderSurfaceSet>(); render_surface_set->set_render_surface(render_surface); render_surface_set->set_render_depth_stencil_surface(depth_surface); ASSERT_TRUE(render_surface_set->ValidateBoundSurfaces()); RenderContext render_context(g_renderer); const RenderSurface* old_render_surface = NULL; const RenderDepthStencilSurface* old_depth_surface = NULL; renderer()->GetRenderSurfaces(&old_render_surface, &old_depth_surface); render_surface_set->Render(&render_context); const RenderSurface* test_render_surface = NULL; const RenderDepthStencilSurface* test_depth_surface = NULL; renderer()->GetRenderSurfaces(&test_render_surface, &test_depth_surface); ASSERT_TRUE(test_render_surface == render_surface); ASSERT_TRUE(test_depth_surface == depth_surface); render_surface_set->PostRender(&render_context); renderer()->GetRenderSurfaces(&test_render_surface, &test_depth_surface); ASSERT_TRUE(test_render_surface == old_render_surface); ASSERT_TRUE(test_depth_surface == old_depth_surface); } } // namespace o3d <commit_msg>Fix syntax accessing enum scoped to class, to fix GCC builds. Review URL: http://codereview.chromium.org/183007<commit_after>/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "core/cross/precompile.h" #include "tests/common/win/testing_common.h" #include "core/cross/client.h" #include "core/cross/pack.h" #include "core/cross/renderer.h" #include "core/cross/bitmap.h" #include "core/cross/features.h" #include "core/cross/texture.h" #include "core/cross/render_surface.h" #include "core/cross/render_surface_set.h" #include "core/cross/renderer_platform.h" // Defined in testing_common.cc, for each platform. extern o3d::DisplayWindow* g_display_window; namespace o3d { class MockRenderer { public: explicit MockRenderer(Renderer* renderer) : renderer_(renderer) {} virtual ~MockRenderer() {} void StartRendering() { renderer_->set_rendering(true); } void FinishRendering() { renderer_->set_rendering(false); } void SetRenderSurfaces(const RenderSurface* surface, const RenderDepthStencilSurface* depth_surface) { renderer_->SetRenderSurfaces(surface, depth_surface); } void GetRenderSurfaces(const RenderSurface** surface, const RenderDepthStencilSurface** depth_surface) { renderer_->GetRenderSurfaces(surface, depth_surface); } private: Renderer* renderer_; }; class RenderSurfaceTest : public testing::Test { public: RenderSurfaceTest() : object_manager_(g_service_locator) {} ServiceLocator* service_locator() { return service_locator_; } MockRenderer* renderer() { return renderer_; } protected: virtual void SetUp() { service_locator_ = new ServiceLocator; features_ = new Features(service_locator_); pack_ = object_manager_->CreatePack(); renderer_ = new MockRenderer(g_renderer); renderer_->StartRendering(); } virtual void TearDown() { renderer_->FinishRendering(); pack_->Destroy(); delete features_; delete service_locator_; delete renderer_; } Pack* pack() { return pack_; } ServiceDependency<ObjectManager> object_manager_; ServiceLocator* service_locator_; Features* features_; Pack* pack_; MockRenderer* renderer_; }; // Test that non PoT textures can't make render surfaces TEST_F(RenderSurfaceTest, NonPowerOfTwoRenderSurfaceEnabled) { Texture2D* texture = pack()->CreateTexture2D(20, 32, Texture::ARGB8, 2, true); ASSERT_TRUE(NULL == texture); } // Test that a render surface can be created TEST_F(RenderSurfaceTest, CreateRenderSurfaceFromTexture2D) { Texture2D* texture = pack()->CreateTexture2D(16, 32, Texture::ARGB8, 2, true); ASSERT_TRUE(NULL != texture); RenderSurface::Ref render_surface = texture->GetRenderSurface(0); ASSERT_TRUE(NULL != render_surface); ASSERT_TRUE(NULL != render_surface->texture()); ASSERT_EQ(render_surface->width(), 16); ASSERT_EQ(render_surface->height(), 32); } TEST_F(RenderSurfaceTest, CreateRenderSurfaceFromTextureCUBE) { TextureCUBE* texture = pack()->CreateTextureCUBE(16, Texture::ARGB8, 2, true); ASSERT_TRUE(NULL != texture); RenderSurface::Ref render_surface = texture->GetRenderSurface( TextureCUBE::FACE_POSITIVE_X, 0); ASSERT_TRUE(NULL != render_surface); ASSERT_TRUE(NULL != render_surface->texture()); ASSERT_EQ(render_surface->width(), 16); ASSERT_EQ(render_surface->height(), 16); } TEST_F(RenderSurfaceTest, SwapRenderSurfaces) { Texture2D* texture = pack()->CreateTexture2D(16, 32, Texture::ARGB8, 2, true); ASSERT_TRUE(NULL != texture); RenderSurface::Ref render_surface = texture->GetRenderSurface(0); ASSERT_TRUE(NULL != render_surface); ASSERT_TRUE(texture == render_surface->texture()); RenderDepthStencilSurface* depth_surface = pack()->CreateDepthStencilSurface(16, 32); // Now swap surfaces. renderer()->SetRenderSurfaces(render_surface, depth_surface); const RenderSurface* test_render_surface = NULL; const RenderDepthStencilSurface* test_depth_surface = NULL; renderer()->GetRenderSurfaces(&test_render_surface, &test_depth_surface); ASSERT_TRUE(test_render_surface == render_surface); ASSERT_TRUE(test_depth_surface == depth_surface); } TEST_F(RenderSurfaceTest, SetBackSurfaces) { Texture2D* texture = pack()->CreateTexture2D(16, 32, Texture::ARGB8, 2, true); ASSERT_TRUE(NULL != texture); RenderSurface::Ref render_surface = texture->GetRenderSurface(0); ASSERT_TRUE(NULL != render_surface); ASSERT_TRUE(texture == render_surface->texture()); RenderDepthStencilSurface* depth_surface = pack()->CreateDepthStencilSurface(16, 32); // Save the original surfaces for comparison. const RenderSurface* original_render_surface = NULL; const RenderDepthStencilSurface* original_depth_surface = NULL; renderer()->GetRenderSurfaces(&original_render_surface, &original_depth_surface); // Now swap surfaces. renderer()->SetRenderSurfaces(render_surface, depth_surface); // Return the back buffers renderer()->SetRenderSurfaces(NULL, NULL); // Get the original surfaces again for comparison. const RenderSurface* restored_render_surface = NULL; const RenderDepthStencilSurface* restored_depth_surface = NULL; renderer()->GetRenderSurfaces(&original_render_surface, &original_depth_surface); ASSERT_TRUE(original_render_surface == restored_render_surface); ASSERT_TRUE(original_depth_surface == restored_depth_surface); } TEST_F(RenderSurfaceTest, RenderSurfaceSetTest) { Texture2D* texture = pack()->CreateTexture2D(16, 32, Texture::ARGB8, 2, true); ASSERT_TRUE(NULL != texture); RenderSurface::Ref render_surface = texture->GetRenderSurface(0); ASSERT_TRUE(NULL != render_surface); ASSERT_TRUE(texture == render_surface->texture()); RenderDepthStencilSurface* depth_surface = pack()->CreateDepthStencilSurface(16, 32); RenderSurfaceSet* render_surface_set = pack()->Create<RenderSurfaceSet>(); render_surface_set->set_render_surface(render_surface); render_surface_set->set_render_depth_stencil_surface(depth_surface); ASSERT_TRUE(render_surface_set->ValidateBoundSurfaces()); RenderContext render_context(g_renderer); const RenderSurface* old_render_surface = NULL; const RenderDepthStencilSurface* old_depth_surface = NULL; renderer()->GetRenderSurfaces(&old_render_surface, &old_depth_surface); render_surface_set->Render(&render_context); const RenderSurface* test_render_surface = NULL; const RenderDepthStencilSurface* test_depth_surface = NULL; renderer()->GetRenderSurfaces(&test_render_surface, &test_depth_surface); ASSERT_TRUE(test_render_surface == render_surface); ASSERT_TRUE(test_depth_surface == depth_surface); render_surface_set->PostRender(&render_context); renderer()->GetRenderSurfaces(&test_render_surface, &test_depth_surface); ASSERT_TRUE(test_render_surface == old_render_surface); ASSERT_TRUE(test_depth_surface == old_depth_surface); } } // namespace o3d <|endoftext|>
<commit_before>/* * StepParameters.hpp * * Created on: Feb 18, 2016 * Author: Péter Fankhauser * Institute: ETH Zurich, Autonomous Systems Lab */ #pragma once #include "free_gait_core/TypeDefs.hpp" #include "free_gait_core/step/StepCompleter.hpp" namespace free_gait { class StepParameters { public: StepParameters() {} virtual ~StepParameters() {}; friend class StepCompleter; protected: struct FootstepParameters { std::string profileType = "triangle"; double profileHeight = 0.08; double averageVelocity = 0.8; double liftOffSpeed = 0.06; double touchdownSpeed = 0.04; double minimumDuration_ = 0.1; // TODO Debug. } footTargetParameters; struct EndEffectorTargetParameters { double averageVelocity = 0.15; double minimumDuration_ = 0.1; } endEffectorTargetParameters; struct LegModeParameters { double duration = 0.5; std::string frameId = "base"; } legModeParameters; struct BaseAutoParameters { double averageLinearVelocity = 0.18; double averageAngularVelocity = 0.32; double supportMargin = 0.05; double minimumDuration = 0.3; PlanarStance nominalPlanarStanceInBaseFrame; BaseAutoParameters() { Position2 position; position << 0.385, 0.25; nominalPlanarStanceInBaseFrame.emplace(LimbEnum::LF_LEG, position); nominalPlanarStanceInBaseFrame.emplace(LimbEnum::RF_LEG, Position2(Eigen::Vector2d(position(0), -position(1)))); nominalPlanarStanceInBaseFrame.emplace(LimbEnum::LH_LEG, Position2(Eigen::Vector2d(-position(0), position(1)))); nominalPlanarStanceInBaseFrame.emplace(LimbEnum::RH_LEG, Position2(Eigen::Vector2d(-position(0), -position(1)))); } } baseAutoParameters; struct BaseTargetParameters { double averageLinearVelocity = 0.05; double averageAngularVelocity = 0.1; double minimumDuration = 0.7; } baseTargetParameters; struct BaseTrajectoryParameters { BaseTrajectoryParameters() { } } baseTrajectoryParameters; }; } /* namespace */ <commit_msg>Parameter changes to default steppingn values from real robot.<commit_after>/* * StepParameters.hpp * * Created on: Feb 18, 2016 * Author: Péter Fankhauser * Institute: ETH Zurich, Autonomous Systems Lab */ #pragma once #include "free_gait_core/TypeDefs.hpp" #include "free_gait_core/step/StepCompleter.hpp" namespace free_gait { class StepParameters { public: StepParameters() {} virtual ~StepParameters() {}; friend class StepCompleter; protected: struct FootstepParameters { std::string profileType = "triangle"; double profileHeight = 0.08; double averageVelocity = 0.8; double liftOffSpeed = 0.20; double touchdownSpeed = 0.2; double minimumDuration_ = 0.1; // TODO Debug. } footTargetParameters; struct EndEffectorTargetParameters { double averageVelocity = 0.15; double minimumDuration_ = 0.1; } endEffectorTargetParameters; struct LegModeParameters { double duration = 0.5; std::string frameId = "base"; } legModeParameters; struct BaseAutoParameters { double averageLinearVelocity = 0.25; double averageAngularVelocity = 0.4; double supportMargin = 0.05; double minimumDuration = 0.3; PlanarStance nominalPlanarStanceInBaseFrame; BaseAutoParameters() { Position2 position; position << 0.385, 0.25; nominalPlanarStanceInBaseFrame.emplace(LimbEnum::LF_LEG, position); nominalPlanarStanceInBaseFrame.emplace(LimbEnum::RF_LEG, Position2(Eigen::Vector2d(position(0), -position(1)))); nominalPlanarStanceInBaseFrame.emplace(LimbEnum::LH_LEG, Position2(Eigen::Vector2d(-position(0), position(1)))); nominalPlanarStanceInBaseFrame.emplace(LimbEnum::RH_LEG, Position2(Eigen::Vector2d(-position(0), -position(1)))); } } baseAutoParameters; struct BaseTargetParameters { double averageLinearVelocity = 0.05; double averageAngularVelocity = 0.1; double minimumDuration = 0.7; } baseTargetParameters; struct BaseTrajectoryParameters { BaseTrajectoryParameters() { } } baseTrajectoryParameters; }; } /* namespace */ <|endoftext|>
<commit_before>/* * Lua_Service_Wrapper.cpp * * Copyright (C) 2020 by MegaMol Team * Alle Rechte vorbehalten. */ // TODO: we need this #define because inclusion of LuaHostService.h leads to windows header inclusion errors. // this stems from linking ZMQ via CMake now being PUBLIC in the core lib. i dont know how to solve this "the right way". #define _WINSOCKAPI_ #include "Lua_Service_Wrapper.hpp" #include "mmcore/utility/LuaHostService.h" #include "Screenshots.h" #include "FrameStatistics.h" #include "WindowManipulation.h" // local logging wrapper for your convenience until central MegaMol logger established #include "mmcore/utility/log/Log.h" static void log(const char* text) { const std::string msg = "Lua_Service_Wrapper: " + std::string(text) + "\n"; megamol::core::utility::log::Log::DefaultLog.WriteInfo(msg.c_str()); } static void log(std::string text) { log(text.c_str()); } namespace { // used to abort a service callback if we are already inside a service wrapper callback struct RecursionGuard { int& state; RecursionGuard(int& s) : state{s} { state++; } ~RecursionGuard() { state--; } bool abort() { return state > 1; } }; } namespace megamol { namespace frontend { Lua_Service_Wrapper::Lua_Service_Wrapper() { // init members to default states } Lua_Service_Wrapper::~Lua_Service_Wrapper() { // clean up raw pointers you allocated with new, which is bad practice and nobody does } bool Lua_Service_Wrapper::init(void* configPtr) { if (configPtr == nullptr) return false; return init(*static_cast<Config*>(configPtr)); } #define luaAPI (*m_config.lua_api_ptr) #define m_network_host reinterpret_cast<megamol::core::utility::LuaHostNetworkConnectionsBroker*>(m_network_host_pimpl.get()) bool Lua_Service_Wrapper::init(const Config& config) { if (!config.lua_api_ptr) { log("failed initialization because LuaAPI is nullptr"); return false; } m_config = config; m_executeLuaScript_resource = [&](std::string const& script) -> std::tuple<bool,std::string> { std::string result_str; bool result_b = luaAPI.RunString(script, result_str); return {result_b, result_str}; }; m_setScriptPath_resource = [&](std::string const& script_path) -> void { luaAPI.SetScriptPath(script_path); }; this->m_providedResourceReferences = { {"LuaScriptPaths", m_scriptpath_resource}, {"ExecuteLuaScript", m_executeLuaScript_resource}, {"SetScriptPath", m_setScriptPath_resource} }; this->m_requestedResourcesNames = { "FrontendResourcesList", "GLFrontbufferToPNG_ScreenshotTrigger", // for screenshots "FrameStatistics", // for LastFrameTime "WindowManipulation" // for Framebuffer resize }; //= {"ZMQ_Context"}; m_network_host_pimpl = std::unique_ptr<void, std::function<void(void*)>>( new megamol::core::utility::LuaHostNetworkConnectionsBroker{}, [](void* ptr) { delete reinterpret_cast<megamol::core::utility::LuaHostNetworkConnectionsBroker*>(ptr); } ); bool host_ok = m_network_host->spawn_connection_broker(m_config.host_address, m_config.retry_socket_port); if (host_ok) { log("initialized successfully"); } else { log("failed to start lua host"); } return host_ok; } void Lua_Service_Wrapper::close() { m_config = {}; // default to nullptr m_network_host->close(); } std::vector<FrontendResource>& Lua_Service_Wrapper::getProvidedResources() { return m_providedResourceReferences; } const std::vector<std::string> Lua_Service_Wrapper::getRequestedResourceNames() const { return m_requestedResourcesNames; } void Lua_Service_Wrapper::setRequestedResources(std::vector<FrontendResource> resources) { // TODO: do something with ZMQ resource we get here m_requestedResourceReferences = resources; megamol::core::LuaAPI::LuaCallbacks callbacks; callbacks.mmListResources_callback_= resources[0].getResource<std::function< std::vector<std::string> (void)> >(); callbacks.mmScreenshot_callback_ = m_requestedResourceReferences[1].getResource<std::function<bool(std::string const&)> >(); callbacks.mmLastFrameTime_callback_ = [&]() { auto& frame_statistics = m_requestedResourceReferences[3].getResource<megamol::frontend_resources::FrameStatistics>(); return static_cast<float>(frame_statistics.last_rendered_frame_time_milliseconds); }; callbacks.mmSetFramebufferSize_callback_ = [&](unsigned int w, unsigned int h) { auto& window_manipulation = m_requestedResourceReferences[4].getResource<megamol::frontend_resources::WindowManipulation>(); window_manipulation.set_framebuffer_size(w, h); }; callbacks.mmSetWindowPosition_callback_ = [&](unsigned int x, unsigned int y) { auto& window_manipulation = m_requestedResourceReferences[4].getResource<megamol::frontend_resources::WindowManipulation>(); window_manipulation.set_window_position(x, y); }; callbacks.mmSetFullscreen_callback_ = [&](bool fullscreen) { auto& window_manipulation = m_requestedResourceReferences[4].getResource<megamol::frontend_resources::WindowManipulation>(); window_manipulation.set_fullscreen(fullscreen?frontend_resources::WindowManipulation::Fullscreen::Maximize:frontend_resources::WindowManipulation::Fullscreen::Restore); }; callbacks.mmSetVsync_callback_= [&](bool state) { auto& window_manipulation = m_requestedResourceReferences[4].getResource<megamol::frontend_resources::WindowManipulation>(); window_manipulation.set_swap_interval(state ? 1 : 0); }; luaAPI.SetCallbacks(callbacks); } // -------- main loop callbacks --------- #define recursion_guard \ RecursionGuard rg{m_service_recursion_depth}; \ if (rg.abort()) return; void Lua_Service_Wrapper::updateProvidedResources() { recursion_guard; // we want lua to be the first thing executed in main loop // so we do all the lua work here m_scriptpath_resource.lua_script_paths.clear(); m_scriptpath_resource.lua_script_paths.push_back(luaAPI.GetScriptPath()); bool need_to_shutdown = false; // e.g. mmQuit should set this to true // fetch Lua requests from ZMQ queue, execute, and give back result if (!m_network_host->request_queue.empty()) { auto lua_requests = std::move(m_network_host->get_request_queue()); std::string result; while (!lua_requests.empty()) { auto& request = lua_requests.front(); luaAPI.RunString(request.request, result); request.answer_promise.get().set_value(result); lua_requests.pop(); result.clear(); } } need_to_shutdown |= luaAPI.getShutdown(); if (need_to_shutdown) this->setShutdown(); } void Lua_Service_Wrapper::digestChangedRequestedResources() { recursion_guard; } void Lua_Service_Wrapper::resetProvidedResources() { recursion_guard; } void Lua_Service_Wrapper::preGraphRender() { recursion_guard; // this gets called right before the graph is told to render something // e.g. you can start a start frame timer here // rendering via MegaMol View is called after this function finishes // in the end this calls the equivalent of ::mmcRenderView(hView, &renderContext) // which leads to view.Render() } void Lua_Service_Wrapper::postGraphRender() { recursion_guard; // the graph finished rendering and you may more stuff here // e.g. end frame timer // update window name // swap buffers, glClear } } // namespace frontend } // namespace megamol <commit_msg>Lua Service Wrapper: fix resource access indices<commit_after>/* * Lua_Service_Wrapper.cpp * * Copyright (C) 2020 by MegaMol Team * Alle Rechte vorbehalten. */ // TODO: we need this #define because inclusion of LuaHostService.h leads to windows header inclusion errors. // this stems from linking ZMQ via CMake now being PUBLIC in the core lib. i dont know how to solve this "the right way". #define _WINSOCKAPI_ #include "Lua_Service_Wrapper.hpp" #include "mmcore/utility/LuaHostService.h" #include "Screenshots.h" #include "FrameStatistics.h" #include "WindowManipulation.h" // local logging wrapper for your convenience until central MegaMol logger established #include "mmcore/utility/log/Log.h" static void log(const char* text) { const std::string msg = "Lua_Service_Wrapper: " + std::string(text) + "\n"; megamol::core::utility::log::Log::DefaultLog.WriteInfo(msg.c_str()); } static void log(std::string text) { log(text.c_str()); } namespace { // used to abort a service callback if we are already inside a service wrapper callback struct RecursionGuard { int& state; RecursionGuard(int& s) : state{s} { state++; } ~RecursionGuard() { state--; } bool abort() { return state > 1; } }; } namespace megamol { namespace frontend { Lua_Service_Wrapper::Lua_Service_Wrapper() { // init members to default states } Lua_Service_Wrapper::~Lua_Service_Wrapper() { // clean up raw pointers you allocated with new, which is bad practice and nobody does } bool Lua_Service_Wrapper::init(void* configPtr) { if (configPtr == nullptr) return false; return init(*static_cast<Config*>(configPtr)); } #define luaAPI (*m_config.lua_api_ptr) #define m_network_host reinterpret_cast<megamol::core::utility::LuaHostNetworkConnectionsBroker*>(m_network_host_pimpl.get()) bool Lua_Service_Wrapper::init(const Config& config) { if (!config.lua_api_ptr) { log("failed initialization because LuaAPI is nullptr"); return false; } m_config = config; m_executeLuaScript_resource = [&](std::string const& script) -> std::tuple<bool,std::string> { std::string result_str; bool result_b = luaAPI.RunString(script, result_str); return {result_b, result_str}; }; m_setScriptPath_resource = [&](std::string const& script_path) -> void { luaAPI.SetScriptPath(script_path); }; this->m_providedResourceReferences = { {"LuaScriptPaths", m_scriptpath_resource}, {"ExecuteLuaScript", m_executeLuaScript_resource}, {"SetScriptPath", m_setScriptPath_resource} }; this->m_requestedResourcesNames = { "FrontendResourcesList", "GLFrontbufferToPNG_ScreenshotTrigger", // for screenshots "FrameStatistics", // for LastFrameTime "WindowManipulation" // for Framebuffer resize }; //= {"ZMQ_Context"}; m_network_host_pimpl = std::unique_ptr<void, std::function<void(void*)>>( new megamol::core::utility::LuaHostNetworkConnectionsBroker{}, [](void* ptr) { delete reinterpret_cast<megamol::core::utility::LuaHostNetworkConnectionsBroker*>(ptr); } ); bool host_ok = m_network_host->spawn_connection_broker(m_config.host_address, m_config.retry_socket_port); if (host_ok) { log("initialized successfully"); } else { log("failed to start lua host"); } return host_ok; } void Lua_Service_Wrapper::close() { m_config = {}; // default to nullptr m_network_host->close(); } std::vector<FrontendResource>& Lua_Service_Wrapper::getProvidedResources() { return m_providedResourceReferences; } const std::vector<std::string> Lua_Service_Wrapper::getRequestedResourceNames() const { return m_requestedResourcesNames; } void Lua_Service_Wrapper::setRequestedResources(std::vector<FrontendResource> resources) { // TODO: do something with ZMQ resource we get here m_requestedResourceReferences = resources; megamol::core::LuaAPI::LuaCallbacks callbacks; callbacks.mmListResources_callback_= resources[0].getResource<std::function< std::vector<std::string> (void)> >(); callbacks.mmScreenshot_callback_ = m_requestedResourceReferences[1].getResource<std::function<bool(std::string const&)> >(); callbacks.mmLastFrameTime_callback_ = [&]() { auto& frame_statistics = m_requestedResourceReferences[2].getResource<megamol::frontend_resources::FrameStatistics>(); return static_cast<float>(frame_statistics.last_rendered_frame_time_milliseconds); }; callbacks.mmSetFramebufferSize_callback_ = [&](unsigned int w, unsigned int h) { auto& window_manipulation = m_requestedResourceReferences[3].getResource<megamol::frontend_resources::WindowManipulation>(); window_manipulation.set_framebuffer_size(w, h); }; callbacks.mmSetWindowPosition_callback_ = [&](unsigned int x, unsigned int y) { auto& window_manipulation = m_requestedResourceReferences[3].getResource<megamol::frontend_resources::WindowManipulation>(); window_manipulation.set_window_position(x, y); }; callbacks.mmSetFullscreen_callback_ = [&](bool fullscreen) { auto& window_manipulation = m_requestedResourceReferences[3].getResource<megamol::frontend_resources::WindowManipulation>(); window_manipulation.set_fullscreen(fullscreen?frontend_resources::WindowManipulation::Fullscreen::Maximize:frontend_resources::WindowManipulation::Fullscreen::Restore); }; callbacks.mmSetVsync_callback_= [&](bool state) { auto& window_manipulation = m_requestedResourceReferences[3].getResource<megamol::frontend_resources::WindowManipulation>(); window_manipulation.set_swap_interval(state ? 1 : 0); }; luaAPI.SetCallbacks(callbacks); } // -------- main loop callbacks --------- #define recursion_guard \ RecursionGuard rg{m_service_recursion_depth}; \ if (rg.abort()) return; void Lua_Service_Wrapper::updateProvidedResources() { recursion_guard; // we want lua to be the first thing executed in main loop // so we do all the lua work here m_scriptpath_resource.lua_script_paths.clear(); m_scriptpath_resource.lua_script_paths.push_back(luaAPI.GetScriptPath()); bool need_to_shutdown = false; // e.g. mmQuit should set this to true // fetch Lua requests from ZMQ queue, execute, and give back result if (!m_network_host->request_queue.empty()) { auto lua_requests = std::move(m_network_host->get_request_queue()); std::string result; while (!lua_requests.empty()) { auto& request = lua_requests.front(); luaAPI.RunString(request.request, result); request.answer_promise.get().set_value(result); lua_requests.pop(); result.clear(); } } need_to_shutdown |= luaAPI.getShutdown(); if (need_to_shutdown) this->setShutdown(); } void Lua_Service_Wrapper::digestChangedRequestedResources() { recursion_guard; } void Lua_Service_Wrapper::resetProvidedResources() { recursion_guard; } void Lua_Service_Wrapper::preGraphRender() { recursion_guard; // this gets called right before the graph is told to render something // e.g. you can start a start frame timer here // rendering via MegaMol View is called after this function finishes // in the end this calls the equivalent of ::mmcRenderView(hView, &renderContext) // which leads to view.Render() } void Lua_Service_Wrapper::postGraphRender() { recursion_guard; // the graph finished rendering and you may more stuff here // e.g. end frame timer // update window name // swap buffers, glClear } } // namespace frontend } // namespace megamol <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/renderer_host/plugin_info_message_filter.h" #include "base/bind.h" #include "base/metrics/histogram.h" #include "base/utf_string_conversions.h" #include "chrome/browser/content_settings/content_settings_utils.h" #include "chrome/browser/content_settings/host_content_settings_map.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_content_client.h" #include "chrome/common/content_settings.h" #include "chrome/common/pref_names.h" #include "chrome/common/render_messages.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/plugin_service.h" #include "content/public/browser/plugin_service_filter.h" #include "googleurl/src/gurl.h" #include "webkit/plugins/npapi/plugin_group.h" #include "webkit/plugins/npapi/plugin_list.h" #if defined(ENABLE_PLUGIN_INSTALLATION) #include "chrome/browser/plugin_finder.h" #include "chrome/browser/plugin_installer.h" #endif using content::PluginService; using webkit::WebPluginInfo; PluginInfoMessageFilter::Context::Context(int render_process_id, Profile* profile) : render_process_id_(render_process_id), resource_context_(profile->GetResourceContext()), host_content_settings_map_(profile->GetHostContentSettingsMap()) { allow_outdated_plugins_.Init(prefs::kPluginsAllowOutdated, profile->GetPrefs(), NULL); allow_outdated_plugins_.MoveToThread(content::BrowserThread::IO); always_authorize_plugins_.Init(prefs::kPluginsAlwaysAuthorize, profile->GetPrefs(), NULL); always_authorize_plugins_.MoveToThread(content::BrowserThread::IO); } PluginInfoMessageFilter::Context::Context() : render_process_id_(0), resource_context_(NULL), host_content_settings_map_(NULL) { } PluginInfoMessageFilter::Context::~Context() { } PluginInfoMessageFilter::PluginInfoMessageFilter( int render_process_id, Profile* profile) : context_(render_process_id, profile), weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) { } bool PluginInfoMessageFilter::OnMessageReceived(const IPC::Message& message, bool* message_was_ok) { IPC_BEGIN_MESSAGE_MAP_EX(PluginInfoMessageFilter, message, *message_was_ok) IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_GetPluginInfo, OnGetPluginInfo) IPC_MESSAGE_UNHANDLED(return false) IPC_END_MESSAGE_MAP() return true; } void PluginInfoMessageFilter::OnDestruct() const { const_cast<PluginInfoMessageFilter*>(this)-> weak_ptr_factory_.DetachFromThread(); const_cast<PluginInfoMessageFilter*>(this)-> weak_ptr_factory_.InvalidateWeakPtrs(); // Destroy on the UI thread because we contain a |PrefMember|. content::BrowserThread::DeleteOnUIThread::Destruct(this); } PluginInfoMessageFilter::~PluginInfoMessageFilter() {} struct PluginInfoMessageFilter::GetPluginInfo_Params { int render_view_id; GURL url; GURL top_origin_url; std::string mime_type; }; void PluginInfoMessageFilter::OnGetPluginInfo( int render_view_id, const GURL& url, const GURL& top_origin_url, const std::string& mime_type, IPC::Message* reply_msg) { GetPluginInfo_Params params = { render_view_id, url, top_origin_url, mime_type }; PluginService::GetInstance()->GetPlugins( base::Bind(&PluginInfoMessageFilter::PluginsLoaded, weak_ptr_factory_.GetWeakPtr(), params, reply_msg)); } void PluginInfoMessageFilter::PluginsLoaded( const GetPluginInfo_Params& params, IPC::Message* reply_msg, const std::vector<WebPluginInfo>& plugins) { ChromeViewHostMsg_GetPluginInfo_Status status; WebPluginInfo plugin; std::string actual_mime_type; // This also fills in |actual_mime_type|. if (!context_.FindEnabledPlugin(params.render_view_id, params.url, params.top_origin_url, params.mime_type, &status, &plugin, &actual_mime_type)) { ChromeViewHostMsg_GetPluginInfo::WriteReplyParams( reply_msg, status, plugin, actual_mime_type); Send(reply_msg); return; } #if defined(ENABLE_PLUGIN_INSTALLATION) PluginFinder::Get(base::Bind(&PluginInfoMessageFilter::GotPluginFinder, this, params, reply_msg, plugin, actual_mime_type)); #else GotPluginFinder(params, reply_msg, plugin, actual_mime_type, NULL); #endif } void PluginInfoMessageFilter::GotPluginFinder( const GetPluginInfo_Params& params, IPC::Message* reply_msg, const WebPluginInfo& plugin, const std::string& actual_mime_type, PluginFinder* plugin_finder) { ChromeViewHostMsg_GetPluginInfo_Status status; context_.DecidePluginStatus(params, plugin, plugin_finder, &status); ChromeViewHostMsg_GetPluginInfo::WriteReplyParams( reply_msg, status, plugin, actual_mime_type); Send(reply_msg); } void PluginInfoMessageFilter::Context::DecidePluginStatus( const GetPluginInfo_Params& params, const WebPluginInfo& plugin, PluginFinder* plugin_finder, ChromeViewHostMsg_GetPluginInfo_Status* status) const { scoped_ptr<webkit::npapi::PluginGroup> group( webkit::npapi::PluginList::Singleton()->GetPluginGroup(plugin)); ContentSetting plugin_setting = CONTENT_SETTING_DEFAULT; bool uses_default_content_setting = true; // Check plug-in content settings. The primary URL is the top origin URL and // the secondary URL is the plug-in URL. GetPluginContentSetting(plugin, params.top_origin_url, params.url, group->identifier(), &plugin_setting, &uses_default_content_setting); DCHECK(plugin_setting != CONTENT_SETTING_DEFAULT); #if defined(ENABLE_PLUGIN_INSTALLATION) PluginInstaller::SecurityStatus plugin_status = PluginInstaller::SECURITY_STATUS_UP_TO_DATE; PluginInstaller* installer = plugin_finder->FindPluginWithIdentifier(group->identifier()); if (installer) plugin_status = installer->GetSecurityStatus(plugin); // Check if the plug-in is outdated. if (plugin_status == PluginInstaller::SECURITY_STATUS_OUT_OF_DATE && !allow_outdated_plugins_.GetValue()) { if (allow_outdated_plugins_.IsManaged()) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedDisallowed; } else { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedBlocked; } return; } // Check if the plug-in requires authorization. if ((plugin_status == PluginInstaller::SECURITY_STATUS_REQUIRES_AUTHORIZATION || PluginService::GetInstance()->IsPluginUnstable(plugin.path)) && plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS && plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS && !always_authorize_plugins_.GetValue() && plugin_setting != CONTENT_SETTING_BLOCK && uses_default_content_setting) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized; return; } #endif if (plugin_setting == CONTENT_SETTING_ASK) status->value = ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay; else if (plugin_setting == CONTENT_SETTING_BLOCK) status->value = ChromeViewHostMsg_GetPluginInfo_Status::kBlocked; } bool PluginInfoMessageFilter::Context::FindEnabledPlugin( int render_view_id, const GURL& url, const GURL& top_origin_url, const std::string& mime_type, ChromeViewHostMsg_GetPluginInfo_Status* status, WebPluginInfo* plugin, std::string* actual_mime_type) const { bool allow_wildcard = true; std::vector<WebPluginInfo> matching_plugins; std::vector<std::string> mime_types; PluginService::GetInstance()->GetPluginInfoArray( url, mime_type, allow_wildcard, &matching_plugins, &mime_types); content::PluginServiceFilter* filter = PluginService::GetInstance()->GetFilter(); bool found = false; for (size_t i = 0; i < matching_plugins.size(); ++i) { bool enabled = !filter || filter->ShouldUsePlugin(render_process_id_, render_view_id, resource_context_, url, top_origin_url, &matching_plugins[i]); if (!found || enabled) { *plugin = matching_plugins[i]; *actual_mime_type = mime_types[i]; if (enabled) { // We have found an enabled plug-in. Return immediately. return true; } // We have found a plug-in, but it's disabled. Keep looking for an // enabled one. found = true; } } // If we're here and have previously found a plug-in, it must have been // disabled. if (found) status->value = ChromeViewHostMsg_GetPluginInfo_Status::kDisabled; else status->value = ChromeViewHostMsg_GetPluginInfo_Status::kNotFound; return false; } void PluginInfoMessageFilter::Context::GetPluginContentSetting( const WebPluginInfo& plugin, const GURL& policy_url, const GURL& plugin_url, const std::string& resource, ContentSetting* setting, bool* uses_default_content_setting) const { // Treat Native Client invocations like Javascript. bool is_nacl_plugin = (plugin.name == ASCIIToUTF16( chrome::ChromeContentClient::kNaClPluginName)); scoped_ptr<base::Value> value; content_settings::SettingInfo info; bool uses_plugin_specific_setting = false; if (is_nacl_plugin) { value.reset( host_content_settings_map_->GetWebsiteSetting( policy_url, policy_url, CONTENT_SETTINGS_TYPE_JAVASCRIPT, std::string(), &info)); } else { value.reset( host_content_settings_map_->GetWebsiteSetting( policy_url, plugin_url, CONTENT_SETTINGS_TYPE_PLUGINS, resource, &info)); if (value.get()) { uses_plugin_specific_setting = true; } else { value.reset(host_content_settings_map_->GetWebsiteSetting( policy_url, plugin_url, CONTENT_SETTINGS_TYPE_PLUGINS, std::string(), &info)); } } *setting = content_settings::ValueToContentSetting(value.get()); *uses_default_content_setting = !uses_plugin_specific_setting && info.primary_pattern == ContentSettingsPattern::Wildcard() && info.secondary_pattern == ContentSettingsPattern::Wildcard(); } <commit_msg>Infobar unknown plugins by default on Linux<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/renderer_host/plugin_info_message_filter.h" #include "base/bind.h" #include "base/metrics/histogram.h" #include "base/utf_string_conversions.h" #include "chrome/browser/content_settings/content_settings_utils.h" #include "chrome/browser/content_settings/host_content_settings_map.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_content_client.h" #include "chrome/common/content_settings.h" #include "chrome/common/pref_names.h" #include "chrome/common/render_messages.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/plugin_service.h" #include "content/public/browser/plugin_service_filter.h" #include "googleurl/src/gurl.h" #include "webkit/plugins/npapi/plugin_group.h" #include "webkit/plugins/npapi/plugin_list.h" #if defined(ENABLE_PLUGIN_INSTALLATION) #include "chrome/browser/plugin_finder.h" #include "chrome/browser/plugin_installer.h" #endif using content::PluginService; using webkit::WebPluginInfo; PluginInfoMessageFilter::Context::Context(int render_process_id, Profile* profile) : render_process_id_(render_process_id), resource_context_(profile->GetResourceContext()), host_content_settings_map_(profile->GetHostContentSettingsMap()) { allow_outdated_plugins_.Init(prefs::kPluginsAllowOutdated, profile->GetPrefs(), NULL); allow_outdated_plugins_.MoveToThread(content::BrowserThread::IO); always_authorize_plugins_.Init(prefs::kPluginsAlwaysAuthorize, profile->GetPrefs(), NULL); always_authorize_plugins_.MoveToThread(content::BrowserThread::IO); } PluginInfoMessageFilter::Context::Context() : render_process_id_(0), resource_context_(NULL), host_content_settings_map_(NULL) { } PluginInfoMessageFilter::Context::~Context() { } PluginInfoMessageFilter::PluginInfoMessageFilter( int render_process_id, Profile* profile) : context_(render_process_id, profile), weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) { } bool PluginInfoMessageFilter::OnMessageReceived(const IPC::Message& message, bool* message_was_ok) { IPC_BEGIN_MESSAGE_MAP_EX(PluginInfoMessageFilter, message, *message_was_ok) IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_GetPluginInfo, OnGetPluginInfo) IPC_MESSAGE_UNHANDLED(return false) IPC_END_MESSAGE_MAP() return true; } void PluginInfoMessageFilter::OnDestruct() const { const_cast<PluginInfoMessageFilter*>(this)-> weak_ptr_factory_.DetachFromThread(); const_cast<PluginInfoMessageFilter*>(this)-> weak_ptr_factory_.InvalidateWeakPtrs(); // Destroy on the UI thread because we contain a |PrefMember|. content::BrowserThread::DeleteOnUIThread::Destruct(this); } PluginInfoMessageFilter::~PluginInfoMessageFilter() {} struct PluginInfoMessageFilter::GetPluginInfo_Params { int render_view_id; GURL url; GURL top_origin_url; std::string mime_type; }; void PluginInfoMessageFilter::OnGetPluginInfo( int render_view_id, const GURL& url, const GURL& top_origin_url, const std::string& mime_type, IPC::Message* reply_msg) { GetPluginInfo_Params params = { render_view_id, url, top_origin_url, mime_type }; PluginService::GetInstance()->GetPlugins( base::Bind(&PluginInfoMessageFilter::PluginsLoaded, weak_ptr_factory_.GetWeakPtr(), params, reply_msg)); } void PluginInfoMessageFilter::PluginsLoaded( const GetPluginInfo_Params& params, IPC::Message* reply_msg, const std::vector<WebPluginInfo>& plugins) { ChromeViewHostMsg_GetPluginInfo_Status status; WebPluginInfo plugin; std::string actual_mime_type; // This also fills in |actual_mime_type|. if (!context_.FindEnabledPlugin(params.render_view_id, params.url, params.top_origin_url, params.mime_type, &status, &plugin, &actual_mime_type)) { ChromeViewHostMsg_GetPluginInfo::WriteReplyParams( reply_msg, status, plugin, actual_mime_type); Send(reply_msg); return; } #if defined(ENABLE_PLUGIN_INSTALLATION) PluginFinder::Get(base::Bind(&PluginInfoMessageFilter::GotPluginFinder, this, params, reply_msg, plugin, actual_mime_type)); #else GotPluginFinder(params, reply_msg, plugin, actual_mime_type, NULL); #endif } void PluginInfoMessageFilter::GotPluginFinder( const GetPluginInfo_Params& params, IPC::Message* reply_msg, const WebPluginInfo& plugin, const std::string& actual_mime_type, PluginFinder* plugin_finder) { ChromeViewHostMsg_GetPluginInfo_Status status; context_.DecidePluginStatus(params, plugin, plugin_finder, &status); ChromeViewHostMsg_GetPluginInfo::WriteReplyParams( reply_msg, status, plugin, actual_mime_type); Send(reply_msg); } void PluginInfoMessageFilter::Context::DecidePluginStatus( const GetPluginInfo_Params& params, const WebPluginInfo& plugin, PluginFinder* plugin_finder, ChromeViewHostMsg_GetPluginInfo_Status* status) const { scoped_ptr<webkit::npapi::PluginGroup> group( webkit::npapi::PluginList::Singleton()->GetPluginGroup(plugin)); ContentSetting plugin_setting = CONTENT_SETTING_DEFAULT; bool uses_default_content_setting = true; // Check plug-in content settings. The primary URL is the top origin URL and // the secondary URL is the plug-in URL. GetPluginContentSetting(plugin, params.top_origin_url, params.url, group->identifier(), &plugin_setting, &uses_default_content_setting); DCHECK(plugin_setting != CONTENT_SETTING_DEFAULT); #if defined(ENABLE_PLUGIN_INSTALLATION) #if defined(OS_LINUX) // On Linux, unknown plugins require authorization. PluginInstaller::SecurityStatus plugin_status = PluginInstaller::SECURITY_STATUS_REQUIRES_AUTHORIZATION; #else PluginInstaller::SecurityStatus plugin_status = PluginInstaller::SECURITY_STATUS_UP_TO_DATE; #endif PluginInstaller* installer = plugin_finder->FindPluginWithIdentifier(group->identifier()); if (installer) plugin_status = installer->GetSecurityStatus(plugin); // Check if the plug-in is outdated. if (plugin_status == PluginInstaller::SECURITY_STATUS_OUT_OF_DATE && !allow_outdated_plugins_.GetValue()) { if (allow_outdated_plugins_.IsManaged()) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedDisallowed; } else { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedBlocked; } return; } // Check if the plug-in requires authorization. if ((plugin_status == PluginInstaller::SECURITY_STATUS_REQUIRES_AUTHORIZATION || PluginService::GetInstance()->IsPluginUnstable(plugin.path)) && plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS && plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS && !always_authorize_plugins_.GetValue() && plugin_setting != CONTENT_SETTING_BLOCK && uses_default_content_setting) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized; return; } #endif if (plugin_setting == CONTENT_SETTING_ASK) status->value = ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay; else if (plugin_setting == CONTENT_SETTING_BLOCK) status->value = ChromeViewHostMsg_GetPluginInfo_Status::kBlocked; } bool PluginInfoMessageFilter::Context::FindEnabledPlugin( int render_view_id, const GURL& url, const GURL& top_origin_url, const std::string& mime_type, ChromeViewHostMsg_GetPluginInfo_Status* status, WebPluginInfo* plugin, std::string* actual_mime_type) const { bool allow_wildcard = true; std::vector<WebPluginInfo> matching_plugins; std::vector<std::string> mime_types; PluginService::GetInstance()->GetPluginInfoArray( url, mime_type, allow_wildcard, &matching_plugins, &mime_types); content::PluginServiceFilter* filter = PluginService::GetInstance()->GetFilter(); bool found = false; for (size_t i = 0; i < matching_plugins.size(); ++i) { bool enabled = !filter || filter->ShouldUsePlugin(render_process_id_, render_view_id, resource_context_, url, top_origin_url, &matching_plugins[i]); if (!found || enabled) { *plugin = matching_plugins[i]; *actual_mime_type = mime_types[i]; if (enabled) { // We have found an enabled plug-in. Return immediately. return true; } // We have found a plug-in, but it's disabled. Keep looking for an // enabled one. found = true; } } // If we're here and have previously found a plug-in, it must have been // disabled. if (found) status->value = ChromeViewHostMsg_GetPluginInfo_Status::kDisabled; else status->value = ChromeViewHostMsg_GetPluginInfo_Status::kNotFound; return false; } void PluginInfoMessageFilter::Context::GetPluginContentSetting( const WebPluginInfo& plugin, const GURL& policy_url, const GURL& plugin_url, const std::string& resource, ContentSetting* setting, bool* uses_default_content_setting) const { // Treat Native Client invocations like Javascript. bool is_nacl_plugin = (plugin.name == ASCIIToUTF16( chrome::ChromeContentClient::kNaClPluginName)); scoped_ptr<base::Value> value; content_settings::SettingInfo info; bool uses_plugin_specific_setting = false; if (is_nacl_plugin) { value.reset( host_content_settings_map_->GetWebsiteSetting( policy_url, policy_url, CONTENT_SETTINGS_TYPE_JAVASCRIPT, std::string(), &info)); } else { value.reset( host_content_settings_map_->GetWebsiteSetting( policy_url, plugin_url, CONTENT_SETTINGS_TYPE_PLUGINS, resource, &info)); if (value.get()) { uses_plugin_specific_setting = true; } else { value.reset(host_content_settings_map_->GetWebsiteSetting( policy_url, plugin_url, CONTENT_SETTINGS_TYPE_PLUGINS, std::string(), &info)); } } *setting = content_settings::ValueToContentSetting(value.get()); *uses_default_content_setting = !uses_plugin_specific_setting && info.primary_pattern == ContentSettingsPattern::Wildcard() && info.secondary_pattern == ContentSettingsPattern::Wildcard(); } <|endoftext|>
<commit_before> #include "drake/systems/plants/RigidBodySystem.h" #include "drake/systems/plants/RigidBodyFrame.h" #include "drake/util/testUtil.h" using namespace std; using namespace Eigen; using namespace Drake; int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "Usage: " << argv[0] << " [options] full_path_to_robot1 full_path_to_robot2 x y z\n" << " The x y z parameters are optional and specify the position" << " of the second robot in the world, which is useful for URDF" << " models)" << std::endl; return 1; } std::shared_ptr<RigidBodyFrame> weld_to_frame; if (argc > 3) { weld_to_frame = allocate_shared<RigidBodyFrame>( aligned_allocator<RigidBodyFrame>(), "world", nullptr, // not used since the robot is attached to the world Eigen::Vector3d(std::stod(argv[3]), std::stod(argv[4]), std::stod(argv[5])), // xyz of the car's root link Eigen::Vector3d(0, 0, 0)); // rpy of the car's root link } else { weld_to_frame = allocate_shared<RigidBodyFrame>( aligned_allocator<RigidBodyFrame>(), "world", nullptr, Isometry3d::Identity()); } auto r1 = make_shared<RigidBodySystem>(); r1->addRobotFromFile(argv[1], DrakeJoint::QUATERNION); auto r2 = make_shared<RigidBodySystem>(); r2->addRobotFromFile(argv[2], DrakeJoint::QUATERNION, weld_to_frame); // for debugging: r1->getRigidBodyTree()->drawKinematicTree("/tmp/r1.dot"); r2->getRigidBodyTree()->drawKinematicTree("/tmp/r2.dot"); // I ran this at the console to see the output: // dot -Tpng -O /tmp/r1.dot; dot -Tpng -O /tmp/r2.dot; open /tmp/r1.dot.png // /tmp/r2.dot.png try { valuecheck(r1->getNumStates(), r2->getNumStates()); } catch(const std::exception& e) { std::cout << "ERROR: Number of states do not match!" << std::endl << " - system 1: " << r1->getNumStates() << std::endl << " - system 2: " << r2->getNumStates() << std::endl; return -1; } try { valuecheck(r1->getNumInputs(), r2->getNumInputs()); } catch(const std::exception& e) { std::cout << "ERROR: Number of inputs do not match!" << std::endl << " - system 1: " << r1->getNumInputs() << std::endl << " - system 2: " << r2->getNumInputs() << std::endl; return -1; } try { valuecheck(r1->getNumOutputs(), r2->getNumOutputs()); } catch(const std::exception& e) { std::cout << "ERROR: Number of outputs do not match!" << std::endl << " - system 1: " << r1->getNumOutputs() << std::endl << " - system 2: " << r2->getNumOutputs() << std::endl; return -1; } // Print the semantics of the states std::cout << "State vector semantics (tree 1):\n" << r1->getStateVectorSemantics() << std::endl; std::cout << "State vector semantics (tree 2):\n" << r2->getStateVectorSemantics() << std::endl; if (*r1->getRigidBodyTree().get() != *r2->getRigidBodyTree().get()) { std::cout << "ERROR: The two rigid body trees are numerically different!" << std::endl; return -1; } else { std::cout << "The two models passed the numerical comparison test." << std::endl; } for (int i = 0; i < 1000; i++) { std::cout << "i = " << i << std::endl; double t = 0.0; VectorXd x = getInitialState(*r1); x[2] = 10.0; // fix vehicle 10m high in the air VectorXd u = VectorXd::Random(r1->getNumInputs()); auto xdot1 = r1->dynamics(t, x, u); auto xdot2 = r2->dynamics(t, x, u); try { valuecheckMatrix(xdot1, xdot2, 1e-8); } catch(const std::runtime_error& re) { std::cout << "Model mismatch!" << std::endl << " - initial state:" << std::endl << x << std::endl << " - inputs (joint torques?):" << std::endl << u << std::endl << " - xdot1:" << std::endl << xdot1.transpose() << std::endl << " - xdot2:" << std::endl << xdot2.transpose() << std::endl << " - error message:" << std::endl << re.what() << std::endl; return -1; } } } <commit_msg>Increase tolerance for dynamics model mismatch. Useful for debugging since it highlights large discrepancies.<commit_after> #include "drake/systems/plants/RigidBodySystem.h" #include "drake/systems/plants/RigidBodyFrame.h" #include "drake/util/testUtil.h" using namespace std; using namespace Eigen; using namespace Drake; int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "Usage: " << argv[0] << " [options] full_path_to_robot1 full_path_to_robot2 x y z\n" << " The x y z parameters are optional and specify the position" << " of the second robot in the world, which is useful for URDF" << " models)" << std::endl; return 1; } std::shared_ptr<RigidBodyFrame> weld_to_frame; if (argc > 3) { weld_to_frame = allocate_shared<RigidBodyFrame>( aligned_allocator<RigidBodyFrame>(), "world", nullptr, // not used since the robot is attached to the world Eigen::Vector3d(std::stod(argv[3]), std::stod(argv[4]), std::stod(argv[5])), // xyz of the car's root link Eigen::Vector3d(0, 0, 0)); // rpy of the car's root link } else { weld_to_frame = allocate_shared<RigidBodyFrame>( aligned_allocator<RigidBodyFrame>(), "world", nullptr, Isometry3d::Identity()); } auto r1 = make_shared<RigidBodySystem>(); r1->addRobotFromFile(argv[1], DrakeJoint::QUATERNION); auto r2 = make_shared<RigidBodySystem>(); r2->addRobotFromFile(argv[2], DrakeJoint::QUATERNION, weld_to_frame); // for debugging: r1->getRigidBodyTree()->drawKinematicTree("/tmp/r1.dot"); r2->getRigidBodyTree()->drawKinematicTree("/tmp/r2.dot"); // I ran this at the console to see the output: // dot -Tpng -O /tmp/r1.dot; dot -Tpng -O /tmp/r2.dot; open /tmp/r1.dot.png // /tmp/r2.dot.png try { valuecheck(r1->getNumStates(), r2->getNumStates()); } catch(const std::exception& e) { std::cout << "ERROR: Number of states do not match!" << std::endl << " - system 1: " << r1->getNumStates() << std::endl << " - system 2: " << r2->getNumStates() << std::endl; return -1; } try { valuecheck(r1->getNumInputs(), r2->getNumInputs()); } catch(const std::exception& e) { std::cout << "ERROR: Number of inputs do not match!" << std::endl << " - system 1: " << r1->getNumInputs() << std::endl << " - system 2: " << r2->getNumInputs() << std::endl; return -1; } try { valuecheck(r1->getNumOutputs(), r2->getNumOutputs()); } catch(const std::exception& e) { std::cout << "ERROR: Number of outputs do not match!" << std::endl << " - system 1: " << r1->getNumOutputs() << std::endl << " - system 2: " << r2->getNumOutputs() << std::endl; return -1; } // Print the semantics of the states std::cout << "State vector semantics (tree 1):\n" << r1->getStateVectorSemantics() << std::endl; std::cout << "State vector semantics (tree 2):\n" << r2->getStateVectorSemantics() << std::endl; if (*r1->getRigidBodyTree().get() != *r2->getRigidBodyTree().get()) { std::cout << "ERROR: The two rigid body trees are numerically different!" << std::endl; return -1; } else { std::cout << "The two models passed the numerical comparison test." << std::endl; } for (int i = 0; i < 1000; i++) { std::cout << "i = " << i << std::endl; double t = 0.0; VectorXd x = getInitialState(*r1); x[2] = 10.0; // fix vehicle 10m high in the air VectorXd u = VectorXd::Random(r1->getNumInputs()); auto xdot1 = r1->dynamics(t, x, u); auto xdot2 = r2->dynamics(t, x, u); try { valuecheckMatrix(xdot1, xdot2, 1); } catch(const std::runtime_error& re) { std::cout << "Model mismatch!" << std::endl << " - initial state:" << std::endl << x << std::endl << " - inputs (joint torques?):" << std::endl << u << std::endl << " - xdot1:" << std::endl << xdot1.transpose() << std::endl << " - xdot2:" << std::endl << xdot2.transpose() << std::endl << " - error message:" << std::endl << re.what() << std::endl; return -1; } } } <|endoftext|>
<commit_before>// Created on: 2007-09-04 // Created by: Andrey BETENEV // Copyright (c) 2007-2012 OPEN CASCADE SAS // // The content of this file is subject to the Open CASCADE Technology Public // License Version 6.5 (the "License"). You may not use the content of this file // except in compliance with the License. Please obtain a copy of the License // at http://www.opencascade.org and read it completely before using this file. // // The Initial Developer of the Original Code is Open CASCADE S.A.S., having its // main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France. // // The Original Code and all software distributed under the License is // distributed on an "AS IS" basis, without warranty of any kind, and the // Initial Developer hereby disclaims all such warranties, including without // limitation, any warranties of merchantability, fitness for a particular // purpose or non-infringement. Please see the License for the specific terms // and conditions governing the rights and limitations under the License. //! @file //! Implementation of some atomic operations (elementary operations //! with data that cannot be interrupted by parallel threads in the //! multithread process) on various platforms //! //! By the moment, only operations necessary for reference counter //! in Standard_Transient objects are implemented. //! //! This is preffered to use fixed size types "int32_t" / "int64_t" for //! correct function declarations however we leave "int" assuming it is 32bits for now. #ifndef _Standard_Atomic_HeaderFile #define _Standard_Atomic_HeaderFile #include <Standard_Macro.hxx> #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__) #if defined(__BORLANDC__) || defined(__MINGW32__) extern "C" { __declspec(dllimport) long __stdcall InterlockedIncrement ( long volatile *lpAddend); __declspec(dllimport) long __stdcall InterlockedDecrement ( long volatile *lpAddend); } #define _InterlockedIncrement InterlockedIncrement #define _InterlockedDecrement InterlockedDecrement #elif defined(_MSC_VER) extern "C" { long _InterlockedIncrement(long volatile* lpAddend); long _InterlockedDecrement(long volatile* lpAddend); } #endif #endif #if defined(_MSC_VER) // force intrinsic instead of WinAPI calls #pragma intrinsic (_InterlockedIncrement) #pragma intrinsic (_InterlockedDecrement) #endif //! Increments atomically integer variable pointed by theValue //! and returns resulting incremented value. static int Standard_Atomic_Increment (volatile int* theValue) { #ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 // mordern g++ compiler (gcc4.4+) // built-in functions available for appropriate CPUs (at least -march=i486 should be specified on x86 platform) return __sync_add_and_fetch (theValue, 1); #elif (defined(_WIN32) || defined(__WIN32__)) // WinAPI function or MSVC intrinsic return _InterlockedIncrement(reinterpret_cast<long volatile*>(theValue)); #elif defined(LIN) // use x86 / x86_64 inline assembly (compatibility with alien compilers / old GCC) int anIncResult; __asm__ __volatile__ ( #if defined(_OCC64) "lock xaddl %%ebx, (%%rax) \n\t" "incl %%ebx \n\t" : "=b" (anIncResult) : "a" (theValue), "b" (1) : "cc", "memory"); #else "lock xaddl %%eax, (%%ecx) \n\t" "incl %%eax \n\t" : "=a" (anIncResult) : "c" (theValue), "a" (1) : "memory"); #endif return anIncResult; #else //#error "Atomic operation doesn't implemented for current platform!" return ++(*theValue); #endif } //! Decrements atomically integer variable pointed by theValue //! and returns resulting decremented value. static int Standard_Atomic_Decrement (volatile int* theValue) { #ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 // mordern g++ compiler (gcc4.4+) // built-in functions available for appropriate CPUs (at least -march=i486 should be specified on x86 platform) return __sync_sub_and_fetch (theValue, 1); #elif (defined(_WIN32) || defined(__WIN32__)) // WinAPI function or MSVC intrinsic return _InterlockedDecrement(reinterpret_cast<long volatile*>(theValue)); #elif defined(LIN) // use x86 / x86_64 inline assembly (compatibility with alien compilers / old GCC) int aDecResult; __asm__ __volatile__ ( #if defined(_OCC64) "lock xaddl %%ebx, (%%rax) \n\t" "decl %%ebx \n\t" : "=b" (aDecResult) : "a" (theValue), "b" (-1) : "cc", "memory"); #else "lock xaddl %%eax, (%%ecx) \n\t" "decl %%eax \n\t" : "=a" (aDecResult) : "c" (theValue), "a" (-1) : "memory"); #endif return aDecResult; #else //#error "Atomic operation doesn't implemented for current platform!" return --(*theValue); #endif } #endif //_Standard_Atomic_HeaderFile <commit_msg>Source code simplification.<commit_after>// Created on: 2007-09-04 // Created by: Andrey BETENEV // Copyright (c) 2007-2012 OPEN CASCADE SAS // // The content of this file is subject to the Open CASCADE Technology Public // License Version 6.5 (the "License"). You may not use the content of this file // except in compliance with the License. Please obtain a copy of the License // at http://www.opencascade.org and read it completely before using this file. // // The Initial Developer of the Original Code is Open CASCADE S.A.S., having its // main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France. // // The Original Code and all software distributed under the License is // distributed on an "AS IS" basis, without warranty of any kind, and the // Initial Developer hereby disclaims all such warranties, including without // limitation, any warranties of merchantability, fitness for a particular // purpose or non-infringement. Please see the License for the specific terms // and conditions governing the rights and limitations under the License. //! @file //! Implementation of some atomic operations (elementary operations //! with data that cannot be interrupted by parallel threads in the //! multithread process) on various platforms //! //! By the moment, only operations necessary for reference counter //! in Standard_Transient objects are implemented. //! //! This is preffered to use fixed size types "int32_t" / "int64_t" for //! correct function declarations however we leave "int" assuming it is 32bits for now. #ifndef _Standard_Atomic_HeaderFile #define _Standard_Atomic_HeaderFile #include <Standard_Macro.hxx> #if (defined(_WIN32) || defined(__WIN32__)) #ifdef _MSC_VER extern "C" { long _InterlockedIncrement(long volatile* lpAddend); long _InterlockedDecrement(long volatile* lpAddend); } // force intrinsic instead of WinAPI calls #pragma intrinsic (_InterlockedIncrement) #pragma intrinsic (_InterlockedDecrement) #else extern "C" { __declspec(dllimport) long __stdcall InterlockedIncrement ( long volatile *lpAddend); __declspec(dllimport) long __stdcall InterlockedDecrement ( long volatile *lpAddend); } #define _InterlockedIncrement InterlockedIncrement #define _InterlockedDecrement InterlockedDecrement #endif #endif //! Increments atomically integer variable pointed by theValue //! and returns resulting incremented value. static int Standard_Atomic_Increment (volatile int* theValue) { #ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 // mordern g++ compiler (gcc4.4+) // built-in functions available for appropriate CPUs (at least -march=i486 should be specified on x86 platform) return __sync_add_and_fetch (theValue, 1); #elif (defined(_WIN32) || defined(__WIN32__)) // WinAPI function or MSVC intrinsic return _InterlockedIncrement(reinterpret_cast<long volatile*>(theValue)); #elif defined(LIN) // use x86 / x86_64 inline assembly (compatibility with alien compilers / old GCC) int anIncResult; __asm__ __volatile__ ( #if defined(_OCC64) "lock xaddl %%ebx, (%%rax) \n\t" "incl %%ebx \n\t" : "=b" (anIncResult) : "a" (theValue), "b" (1) : "cc", "memory"); #else "lock xaddl %%eax, (%%ecx) \n\t" "incl %%eax \n\t" : "=a" (anIncResult) : "c" (theValue), "a" (1) : "memory"); #endif return anIncResult; #else //#error "Atomic operation doesn't implemented for current platform!" return ++(*theValue); #endif } //! Decrements atomically integer variable pointed by theValue //! and returns resulting decremented value. static int Standard_Atomic_Decrement (volatile int* theValue) { #ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 // mordern g++ compiler (gcc4.4+) // built-in functions available for appropriate CPUs (at least -march=i486 should be specified on x86 platform) return __sync_sub_and_fetch (theValue, 1); #elif (defined(_WIN32) || defined(__WIN32__)) // WinAPI function or MSVC intrinsic return _InterlockedDecrement(reinterpret_cast<long volatile*>(theValue)); #elif defined(LIN) // use x86 / x86_64 inline assembly (compatibility with alien compilers / old GCC) int aDecResult; __asm__ __volatile__ ( #if defined(_OCC64) "lock xaddl %%ebx, (%%rax) \n\t" "decl %%ebx \n\t" : "=b" (aDecResult) : "a" (theValue), "b" (-1) : "cc", "memory"); #else "lock xaddl %%eax, (%%ecx) \n\t" "decl %%eax \n\t" : "=a" (aDecResult) : "c" (theValue), "a" (-1) : "memory"); #endif return aDecResult; #else //#error "Atomic operation doesn't implemented for current platform!" return --(*theValue); #endif } #endif //_Standard_Atomic_HeaderFile <|endoftext|>
<commit_before>/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. 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 WARRANNTY OF ANY KIND, EXPRESS OR IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <hc_am.hpp> #include "hip_runtime.h" #include "hcc_detail/hip_hcc.h" #include "hcc_detail/trace_helper.h" // Peer access functions. // There are two flavors: // - one where contexts are specified with hipCtx_t type. // - one where contexts are specified with integer deviceIds, that are mapped to the primary context for that device. // The implementation contains a set of internal ihip* functions which operate on contexts. Then the // public APIs are thin wrappers which call into this internal implementations. // TODO - actually not yet - currently the integer deviceId flavors just call the context APIs. need to fix. /** * HCC returns 0 in *canAccessPeer ; Need to update this function when RT supports P2P */ //--- hipError_t hipDeviceCanAccessPeer (int* canAccessPeer, hipCtx_t thisCtx, hipCtx_t peerCtx) { HIP_INIT_API(canAccessPeer, thisCtx, peerCtx); hipError_t err = hipSuccess; if ((thisCtx != NULL) && (peerCtx != NULL)) { if (thisCtx == peerCtx) { *canAccessPeer = 0; } else { *canAccessPeer = peerCtx->getDevice()->_acc.get_is_peer(thisCtx->getDevice()->_acc); } } else { *canAccessPeer = 0; err = hipErrorInvalidDevice; } return ihipLogStatus(err); } //--- // Disable visibility of this device into memory allocated on peer device. // Remove this device from peer device peerlist. hipError_t ihipDisablePeerAccess (hipCtx_t peerCtx) { HIP_INIT_API(peerCtx); hipError_t err = hipSuccess; auto thisCtx = ihipGetTlsDefaultCtx(); if ((thisCtx != NULL) && (peerCtx != NULL)) { // Return true if thisCtx can access peerCtx's memory: bool canAccessPeer = peerCtx->getDevice()->_acc.get_is_peer(thisCtx->getDevice()->_acc); if (! canAccessPeer) { err = hipErrorInvalidDevice; // P2P not allowed between these devices. } else if (thisCtx == peerCtx) { err = hipErrorInvalidDevice; // Can't disable peer access to self. } else { LockedAccessor_CtxCrit_t peerCrit(peerCtx->criticalData()); bool changed = peerCrit->removePeer(thisCtx); if (changed) { // Update the peers for all memory already saved in the tracker: am_memtracker_update_peers(peerCtx->getDevice()->_acc, peerCrit->peerCnt(), peerCrit->peerAgents()); } else { err = hipErrorPeerAccessNotEnabled; // never enabled P2P access. } } } else { err = hipErrorInvalidDevice; } return ihipLogStatus(err); }; //--- // Allow the current device to see all memory allocated on peerDevice. // This should add this device to the peer-device peer list. hipError_t ihipEnablePeerAccess (hipCtx_t peerCtx, unsigned int flags) { HIP_INIT_API(peerCtx, flags); hipError_t err = hipSuccess; if (flags != 0) { err = hipErrorInvalidValue; } else { auto thisCtx = ihipGetTlsDefaultCtx(); if (thisCtx == peerCtx) { err = hipErrorInvalidDevice; // Can't enable peer access to self. } else if ((thisCtx != NULL) && (peerCtx != NULL)) { LockedAccessor_CtxCrit_t peerCrit(peerCtx->criticalData()); bool isNewPeer = peerCrit->addPeer(thisCtx); if (isNewPeer) { am_memtracker_update_peers(peerCtx->getDevice()->_acc, peerCrit->peerCnt(), peerCrit->peerAgents()); } else { err = hipErrorPeerAccessAlreadyEnabled; } } else { err = hipErrorInvalidDevice; } } return ihipLogStatus(err); } //--- hipError_t hipMemcpyPeer (void* dst, hipCtx_t dstCtx, const void* src, hipCtx_t srcCtx, size_t sizeBytes) { HIP_INIT_API(dst, dstCtx, src, srcCtx, sizeBytes); // HCC has a unified memory architecture so device specifiers are not required. return hipMemcpy(dst, src, sizeBytes, hipMemcpyDefault); }; //--- hipError_t hipMemcpyPeerAsync (void* dst, hipCtx_t dstDevice, const void* src, hipCtx_t srcDevice, size_t sizeBytes, hipStream_t stream) { HIP_INIT_API(dst, dstDevice, src, srcDevice, sizeBytes, stream); // HCC has a unified memory architecture so device specifiers are not required. return hipMemcpyAsync(dst, src, sizeBytes, hipMemcpyDefault, stream); }; //============================================================================= // These are the flavors that accept integer deviceIDs. // Implementations map these to primary contexts and call the internal functions above. //============================================================================= hipError_t hipDeviceCanAccessPeer (int* canAccessPeer, int deviceId, int peerDeviceId) { HIP_INIT_API(canAccessPeer, deviceId, peerDeviceId); return hipDeviceCanAccessPeer(canAccessPeer, ihipGetPrimaryCtx(deviceId), ihipGetPrimaryCtx(peerDeviceId)); } hipError_t hipDeviceDisablePeerAccess (int peerDeviceId) { HIP_INIT_API(peerDeviceId); return ihipDisablePeerAccess(ihipGetPrimaryCtx(peerDeviceId)); } hipError_t hipDeviceEnablePeerAccess (int peerDeviceId, unsigned int flags) { HIP_INIT_API(peerDeviceId, flags); return ihipEnablePeerAccess(ihipGetPrimaryCtx(peerDeviceId), flags); } hipError_t hipMemcpyPeer (void* dst, int dstDevice, const void* src, int srcDevice, size_t sizeBytes) { HIP_INIT_API(dst, dstDevice, src, srcDevice, sizeBytes); return hipMemcpyPeer(dst, ihipGetPrimaryCtx(dstDevice), src, ihipGetPrimaryCtx(srcDevice), sizeBytes); } hipError_t hipMemcpyPeerAsync (void* dst, int dstDevice, const void* src, int srcDevice, size_t sizeBytes, hipStream_t stream) { HIP_INIT_API(dst, dstDevice, src, srcDevice, sizeBytes, stream); return hipMemcpyPeerAsync(dst, ihipGetPrimaryCtx(dstDevice), src, ihipGetPrimaryCtx(srcDevice), sizeBytes, stream); } hipError_t hipCtxEnablePeerAccess (hipCtx_t peerCtx, unsigned int flags) { HIP_INIT_API(peerCtx, flags); return ihipEnablePeerAccess(peerCtx, flags); } hipError_t hipCtxDisablePeerAccess (hipCtx_t peerCtx) { HIP_INIT_API(peerCtx); return ihipDisablePeerAccess(peerCtx); } <commit_msg>Fix HIP_INIT_API and ihipLogStatus calls<commit_after>/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. 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 WARRANNTY OF ANY KIND, EXPRESS OR IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <hc_am.hpp> #include "hip_runtime.h" #include "hcc_detail/hip_hcc.h" #include "hcc_detail/trace_helper.h" // Peer access functions. // There are two flavors: // - one where contexts are specified with hipCtx_t type. // - one where contexts are specified with integer deviceIds, that are mapped to the primary context for that device. // The implementation contains a set of internal ihip* functions which operate on contexts. Then the // public APIs are thin wrappers which call into this internal implementations. // TODO - actually not yet - currently the integer deviceId flavors just call the context APIs. need to fix. /** * HCC returns 0 in *canAccessPeer ; Need to update this function when RT supports P2P */ //--- hipError_t hipDeviceCanAccessPeer (int* canAccessPeer, hipCtx_t thisCtx, hipCtx_t peerCtx) { HIP_INIT_API(canAccessPeer, thisCtx, peerCtx); hipError_t err = hipSuccess; if ((thisCtx != NULL) && (peerCtx != NULL)) { if (thisCtx == peerCtx) { *canAccessPeer = 0; } else { *canAccessPeer = peerCtx->getDevice()->_acc.get_is_peer(thisCtx->getDevice()->_acc); } } else { *canAccessPeer = 0; err = hipErrorInvalidDevice; } return ihipLogStatus(err); } //--- // Disable visibility of this device into memory allocated on peer device. // Remove this device from peer device peerlist. hipError_t ihipDisablePeerAccess (hipCtx_t peerCtx) { hipError_t err = hipSuccess; auto thisCtx = ihipGetTlsDefaultCtx(); if ((thisCtx != NULL) && (peerCtx != NULL)) { bool canAccessPeer = peerCtx->getDevice()->_acc.get_is_peer(thisCtx->getDevice()->_acc); if (! canAccessPeer) { err = hipErrorInvalidDevice; // P2P not allowed between these devices. } else if (thisCtx == peerCtx) { err = hipErrorInvalidDevice; // Can't disable peer access to self. } else { LockedAccessor_CtxCrit_t peerCrit(peerCtx->criticalData()); bool changed = peerCrit->removePeer(thisCtx); if (changed) { // Update the peers for all memory already saved in the tracker: am_memtracker_update_peers(peerCtx->getDevice()->_acc, peerCrit->peerCnt(), peerCrit->peerAgents()); } else { err = hipErrorPeerAccessNotEnabled; // never enabled P2P access. } } } else { err = hipErrorInvalidDevice; } return err; }; //--- // Allow the current device to see all memory allocated on peerCtx. // This should add this device to the peer-device peer list. hipError_t ihipEnablePeerAccess (hipCtx_t peerCtx, unsigned int flags) { hipError_t err = hipSuccess; if (flags != 0) { err = hipErrorInvalidValue; } else { auto thisCtx = ihipGetTlsDefaultCtx(); if (thisCtx == peerCtx) { err = hipErrorInvalidDevice; // Can't enable peer access to self. } else if ((thisCtx != NULL) && (peerCtx != NULL)) { LockedAccessor_CtxCrit_t peerCrit(peerCtx->criticalData()); // Add thisCtx to peerCtx's access list so that new allocations on peer will be made visible to this device: bool isNewPeer = peerCrit->addPeer(thisCtx); if (isNewPeer) { am_memtracker_update_peers(peerCtx->getDevice()->_acc, peerCrit->peerCnt(), peerCrit->peerAgents()); } else { err = hipErrorPeerAccessAlreadyEnabled; } } else { err = hipErrorInvalidDevice; } } return err; } //--- hipError_t hipMemcpyPeer (void* dst, hipCtx_t dstCtx, const void* src, hipCtx_t srcCtx, size_t sizeBytes) { HIP_INIT_API(dst, dstCtx, src, srcCtx, sizeBytes); // TODO - move to ihip memory copy implementaion. // HCC has a unified memory architecture so device specifiers are not required. return hipMemcpy(dst, src, sizeBytes, hipMemcpyDefault); }; //--- hipError_t hipMemcpyPeerAsync (void* dst, hipCtx_t dstDevice, const void* src, hipCtx_t srcDevice, size_t sizeBytes, hipStream_t stream) { HIP_INIT_API(dst, dstDevice, src, srcDevice, sizeBytes, stream); // TODO - move to ihip memory copy implementaion. // HCC has a unified memory architecture so device specifiers are not required. return hipMemcpyAsync(dst, src, sizeBytes, hipMemcpyDefault, stream); }; //============================================================================= // These are the flavors that accept integer deviceIDs. // Implementations map these to primary contexts and call the internal functions above. //============================================================================= hipError_t hipDeviceCanAccessPeer (int* canAccessPeer, int deviceId, int peerDeviceId) { HIP_INIT_API(canAccessPeer, deviceId, peerDeviceId); return hipDeviceCanAccessPeer(canAccessPeer, ihipGetPrimaryCtx(deviceId), ihipGetPrimaryCtx(peerDeviceId)); } hipError_t hipDeviceDisablePeerAccess (int peerDeviceId) { HIP_INIT_API(peerDeviceId); return ihipLogStatus(ihipDisablePeerAccess(ihipGetPrimaryCtx(peerDeviceId))); } hipError_t hipDeviceEnablePeerAccess (int peerDeviceId, unsigned int flags) { HIP_INIT_API(peerDeviceId, flags); return ihipLogStatus(ihipEnablePeerAccess(ihipGetPrimaryCtx(peerDeviceId), flags)); } hipError_t hipMemcpyPeer (void* dst, int dstDevice, const void* src, int srcDevice, size_t sizeBytes) { HIP_INIT_API(dst, dstDevice, src, srcDevice, sizeBytes); return hipMemcpyPeer(dst, ihipGetPrimaryCtx(dstDevice), src, ihipGetPrimaryCtx(srcDevice), sizeBytes); } hipError_t hipMemcpyPeerAsync (void* dst, int dstDevice, const void* src, int srcDevice, size_t sizeBytes, hipStream_t stream) { HIP_INIT_API(dst, dstDevice, src, srcDevice, sizeBytes, stream); return hipMemcpyPeerAsync(dst, ihipGetPrimaryCtx(dstDevice), src, ihipGetPrimaryCtx(srcDevice), sizeBytes, stream); } hipError_t hipCtxEnablePeerAccess (hipCtx_t peerCtx, unsigned int flags) { HIP_INIT_API(peerCtx, flags); return ihipLogStatus(ihipEnablePeerAccess(peerCtx, flags)); } hipError_t hipCtxDisablePeerAccess (hipCtx_t peerCtx) { HIP_INIT_API(peerCtx); return ihipLogStatus(ihipDisablePeerAccess(peerCtx)); } <|endoftext|>
<commit_before>#pragma once #include "depthai-shared/common/CameraBoardSocket.hpp" #include "depthai-shared/common/CameraImageOrientation.hpp" #include "depthai-shared/datatype/RawCameraControl.hpp" #include "depthai-shared/properties/Properties.hpp" namespace dai { /** * Specify properties for ColorCamera such as camera ID, ... */ struct ColorCameraProperties : PropertiesSerializable<Properties, ColorCameraProperties> { static constexpr int AUTO = -1; struct IspScale { int32_t horizNumerator = 0; int32_t horizDenominator = 0; int32_t vertNumerator = 0; int32_t vertDenominator = 0; DEPTHAI_SERIALIZE(IspScale, horizNumerator, horizDenominator, vertNumerator, vertDenominator); }; /** * Select the camera sensor resolution */ enum class SensorResolution : int32_t { THE_1080_P, THE_4_K, THE_12_MP, THE_13_MP, THE_720_P, THE_800_P }; /** * For 24 bit color these can be either RGB or BGR */ enum class ColorOrder : int32_t { BGR, RGB }; /* * Initial controls applied to ColorCamera node */ RawCameraControl initialControl; /** * Which socket will color camera use */ CameraBoardSocket boardSocket = CameraBoardSocket::AUTO; /** * Camera sensor image orientation / pixel readout */ CameraImageOrientation imageOrientation = CameraImageOrientation::AUTO; /** * For 24 bit color these can be either RGB or BGR */ ColorOrder colorOrder = ColorOrder::BGR; /** * Are colors interleaved (R1G1B1, R2G2B2, ...) or planar (R1R2..., G1G2..., B1B2) */ bool interleaved = true; /** * Are values FP16 type (0.0 - 255.0) */ bool fp16 = false; /** * Preview frame output height */ uint32_t previewHeight = 300; /** * Preview frame output width */ uint32_t previewWidth = 300; /** * Preview frame output width */ int32_t videoWidth = AUTO; /** * Preview frame output height */ int32_t videoHeight = AUTO; /** * Preview frame output width */ int32_t stillWidth = AUTO; /** * Preview frame output height */ int32_t stillHeight = AUTO; /** * Select the camera sensor resolution */ SensorResolution resolution = SensorResolution::THE_1080_P; /** * Camera sensor FPS */ float fps = 30.0; /** * Initial sensor crop, -1 signifies center crop */ float sensorCropX = AUTO; float sensorCropY = AUTO; /** * Whether to keep aspect ratio of input (video size) or not */ bool previewKeepAspectRatio = true; /** * Configure scaling for `isp` output. */ IspScale ispScale; }; DEPTHAI_SERIALIZE_EXT(ColorCameraProperties, initialControl, boardSocket, imageOrientation, colorOrder, interleaved, fp16, previewHeight, previewWidth, videoWidth, videoHeight, stillWidth, stillHeight, resolution, fps, sensorCropX, sensorCropY, previewKeepAspectRatio, ispScale); } // namespace dai <commit_msg>Added pool sizes to the properties<commit_after>#pragma once #include "depthai-shared/common/CameraBoardSocket.hpp" #include "depthai-shared/common/CameraImageOrientation.hpp" #include "depthai-shared/datatype/RawCameraControl.hpp" #include "depthai-shared/properties/Properties.hpp" namespace dai { /** * Specify properties for ColorCamera such as camera ID, ... */ struct ColorCameraProperties : PropertiesSerializable<Properties, ColorCameraProperties> { static constexpr int AUTO = -1; struct IspScale { int32_t horizNumerator = 0; int32_t horizDenominator = 0; int32_t vertNumerator = 0; int32_t vertDenominator = 0; DEPTHAI_SERIALIZE(IspScale, horizNumerator, horizDenominator, vertNumerator, vertDenominator); }; /** * Select the camera sensor resolution */ enum class SensorResolution : int32_t { THE_1080_P, THE_4_K, THE_12_MP, THE_13_MP, THE_720_P, THE_800_P }; /** * For 24 bit color these can be either RGB or BGR */ enum class ColorOrder : int32_t { BGR, RGB }; /* * Initial controls applied to ColorCamera node */ RawCameraControl initialControl; /** * Which socket will color camera use */ CameraBoardSocket boardSocket = CameraBoardSocket::AUTO; /** * Camera sensor image orientation / pixel readout */ CameraImageOrientation imageOrientation = CameraImageOrientation::AUTO; /** * For 24 bit color these can be either RGB or BGR */ ColorOrder colorOrder = ColorOrder::BGR; /** * Are colors interleaved (R1G1B1, R2G2B2, ...) or planar (R1R2..., G1G2..., B1B2) */ bool interleaved = true; /** * Are values FP16 type (0.0 - 255.0) */ bool fp16 = false; /** * Preview frame output height */ uint32_t previewHeight = 300; /** * Preview frame output width */ uint32_t previewWidth = 300; /** * Preview frame output width */ int32_t videoWidth = AUTO; /** * Preview frame output height */ int32_t videoHeight = AUTO; /** * Preview frame output width */ int32_t stillWidth = AUTO; /** * Preview frame output height */ int32_t stillHeight = AUTO; /** * Select the camera sensor resolution */ SensorResolution resolution = SensorResolution::THE_1080_P; /** * Camera sensor FPS */ float fps = 30.0; /** * Initial sensor crop, -1 signifies center crop */ float sensorCropX = AUTO; float sensorCropY = AUTO; /** * Whether to keep aspect ratio of input (video size) or not */ bool previewKeepAspectRatio = true; /** * Configure scaling for `isp` output. */ IspScale ispScale; /** * Pool sizes */ int numFramesPoolRaw = 3; int numFramesPoolIsp = 3; int numFramesPoolVideo = 4; int numFramesPoolPreview = 4; int numFramesPoolStill = 4; }; DEPTHAI_SERIALIZE_EXT(ColorCameraProperties, initialControl, boardSocket, imageOrientation, colorOrder, interleaved, fp16, previewHeight, previewWidth, videoWidth, videoHeight, stillWidth, stillHeight, resolution, fps, sensorCropX, sensorCropY, previewKeepAspectRatio, ispScale, numFramesPoolRaw, numFramesPoolIsp, numFramesPoolVideo, numFramesPoolPreview, numFramesPoolStill); } // namespace dai <|endoftext|>
<commit_before>/***************************************************************************** * taglib.cpp: Taglib tag parser/writer ***************************************************************************** * Copyright (C) 2003-2006 the VideoLAN team * $Id$ * * Authors: Clément Stenac <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include <stdlib.h> #include <vlc/vlc.h> #include <vlc_playlist.h> #include <vlc_meta.h> #include <vlc_demux.h> #include <fileref.h> #include <tag.h> #include <tstring.h> #include <id3v2tag.h> #include <mpegfile.h> #include <flacfile.h> #if 0 #include <oggflacfile.h> #endif #include <flacfile.h> #include <flacproperties.h> #include <vorbisfile.h> #include <vorbisproperties.h> #include <uniquefileidentifierframe.h> #if 0 //for artist and album id #include <textidentificationframe.h> #endif static int ReadMeta ( vlc_object_t * ); static int DownloadArt ( vlc_object_t * ); static int WriteMeta ( vlc_object_t * ); vlc_module_begin(); set_capability( "meta reader", 1000 ); set_callbacks( ReadMeta, NULL ); add_submodule(); set_capability( "art downloader", 50 ); set_callbacks( DownloadArt, NULL ); add_submodule(); set_capability( "meta writer", 50 ); set_callbacks( WriteMeta, NULL ); vlc_module_end(); static bool checkID3Image( const TagLib::ID3v2::Tag *tag ) { TagLib::ID3v2::FrameList l = tag->frameListMap()[ "APIC" ]; return !l.isEmpty(); } /* Try detecting embedded art */ static void DetectImage( TagLib::FileRef f, vlc_meta_t *p_meta ) { if( TagLib::MPEG::File *mpeg = dynamic_cast<TagLib::MPEG::File *>(f.file() ) ) { if( mpeg->ID3v2Tag() && checkID3Image( mpeg->ID3v2Tag() ) ) vlc_meta_SetArtURL( p_meta, "APIC" ); } else if( TagLib::FLAC::File *flac = dynamic_cast<TagLib::FLAC::File *>(f.file() ) ) { if( flac->ID3v2Tag() && checkID3Image( flac->ID3v2Tag() ) ) vlc_meta_SetArtURL( p_meta, "APIC" ); } #if 0 /* This needs special additions to taglib */ * else if( TagLib::MP4::File *mp4 = dynamic_cast<TagLib::MP4::File *>( f.file() ) ) { TagLib::MP4::Tag *mp4tag = dynamic_cast<TagLib::MP4::Tag *>( mp4->tag() ); if( mp4tag && mp4tag->cover().size() ) vlc_meta_SetArtURL( p_meta, "MP4C" ); } #endif } static int ReadMeta( vlc_object_t *p_this ) { demux_t *p_demux = (demux_t *)p_this; if( !strncmp( p_demux->psz_access, "file", 4 ) ) { if( !p_demux->p_private ) p_demux->p_private = (void*)vlc_meta_New(); TagLib::FileRef f( p_demux->psz_path ); if( !f.isNull() ) { if( TagLib::Ogg::Vorbis::File *p_ogg_v = dynamic_cast<TagLib::Ogg::Vorbis::File *>(f.file() ) ) { int i_ogg_v_length = p_ogg_v->audioProperties()->length(); input_thread_t *p_input = (input_thread_t *)vlc_object_find( p_demux, VLC_OBJECT_INPUT, FIND_PARENT ); if( p_input ) { input_item_t *p_item = input_GetItem( p_input ); if( p_item ) { vlc_mutex_lock( &p_item->lock ); p_item->i_duration = i_ogg_v_length * 1000000; vlc_mutex_unlock( &p_item->lock ); } vlc_object_release( p_input ); } } #if 0 /* at this moment, taglib is unable to detect ogg/flac files * becauses type detection is based on file extension: * ogg = ogg/vorbis * flac = flac * ø = ogg/flac */ else if( TagLib::Ogg::FLAC::File *p_ogg_f = dynamic_cast<TagLib::Ogg::FLAC::File *>(f.file() ) ) { long i_ogg_f_length = p_ogg_f->streamLength(); input_thread_t *p_input = (input_thread_t *)vlc_object_find( p_demux, VLC_OBJECT_INPUT, FIND_PARENT ); if( p_input ) { input_item_t *p_item = input_GetItem( p_input ); if( p_item ) { vlc_mutex_lock( &p_item->lock ); p_item->i_duration = i_ogg_f_length * 1000000; vlc_mutex_unlock( &p_item->lock ); } vlc_object_release( p_input ); } } #endif else if( TagLib::FLAC::File *p_flac = dynamic_cast<TagLib::FLAC::File *>(f.file() ) ) { long i_flac_length = p_flac->audioProperties()->length(); input_thread_t *p_input = (input_thread_t *)vlc_object_find( p_demux, VLC_OBJECT_INPUT, FIND_PARENT ); if( p_input ) { input_item_t *p_item = input_GetItem( p_input ); if( p_item ) { vlc_mutex_lock( &p_item->lock ); p_item->i_duration = i_flac_length * 1000000; vlc_mutex_unlock( &p_item->lock ); } vlc_object_release( p_input ); } } } if( !f.isNull() && f.tag() && !f.tag()->isEmpty() ) { TagLib::Tag *tag = f.tag(); vlc_meta_t *p_meta = (vlc_meta_t *)(p_demux->p_private ); #define SET( foo, bar ) vlc_meta_Set##foo( p_meta, tag->bar ().toCString(true)) SET( Title, title ); SET( Artist, artist ); SET( Album, album ); // SET( Comment, comment ); SET( Genre, genre ); // SET( Year, year ); Gra, this is an int, need to convert // SET( Tracknum , track ); Same #undef SET if( TagLib::MPEG::File *p_mpeg = dynamic_cast<TagLib::MPEG::File *>(f.file() ) ) { if( p_mpeg->ID3v2Tag() ) { TagLib::ID3v2::Tag *tag = p_mpeg->ID3v2Tag(); TagLib::ID3v2::FrameList list = tag->frameListMap()["UFID"]; TagLib::ID3v2::UniqueFileIdentifierFrame* p_ufid; for( TagLib::ID3v2::FrameList::Iterator iter = list.begin(); iter != list.end(); iter++ ) { p_ufid = dynamic_cast<TagLib::ID3v2::UniqueFileIdentifierFrame*>(*iter); const char *owner = p_ufid->owner().toCString(); if (!strcmp( owner, "http://musicbrainz.org" )) { /* ID3v2 UFID contains up to 64 bytes binary data * but in our case it will be a '\0' * terminated string */ char *psz_ufid = (char*) malloc( 64 ); int j = 0; while( ( j < 63 ) && ( j < p_ufid->identifier().size() ) ) psz_ufid[j] = p_ufid->identifier()[j++]; psz_ufid[j] = '\0'; vlc_meta_SetTrackID( p_meta, psz_ufid ); free( psz_ufid ); } } /* musicbrainz artist and album id: not useful (yet?) */ #if 0 list = tag->frameListMap()["TXXX"]; TagLib::ID3v2::UserTextIdentificationFrame* p_txxx; for( TagLib::ID3v2::FrameList::Iterator iter = list.begin(); iter != list.end(); iter++ ) { p_txxx = dynamic_cast<TagLib::ID3v2::UserTextIdentificationFrame*>(*iter); const char *psz_desc= p_txxx->description().toCString(); if( !strncmp( psz_desc, "MusicBrainz Artist Id", 21 ) ) vlc_meta_SetArtistID( p_meta, p_txxx->fieldList().toString().toCString()); if( !strncmp( psz_desc, "MusicBrainz Album Id", 20 ) ) vlc_meta_SetAlbumID( p_meta, p_txxx->fieldList().toString().toCString()); } #endif } } DetectImage( f, p_meta ); return VLC_SUCCESS; } } return VLC_EGENERIC; } #define SET(a,b) if(b) { \ TagLib::String *psz_##a = new TagLib::String( b, \ TagLib::String::UTF8 ); \ tag->set##a( *psz_##a ); \ delete psz_##a; \ } static int WriteMeta( vlc_object_t *p_this ) { playlist_t *p_playlist = (playlist_t *)p_this; meta_export_t *p_export = (meta_export_t *)p_playlist->p_private; input_item_t *p_item = p_export->p_item; if( p_item == NULL ) { msg_Err( p_this, "Can't save meta data of an empty input" ); return VLC_EGENERIC; } TagLib::FileRef f( p_export->psz_file ); if( !f.isNull() && f.tag() ) { msg_Dbg( p_this, "Updating metadata for %s", p_export->psz_file ); TagLib::Tag *tag = f.tag(); char *psz_meta; psz_meta = input_item_GetArtist( p_item ); SET( Artist, psz_meta ); free( psz_meta ); psz_meta = input_item_GetTitle( p_item ); if( !psz_meta ) psz_meta = input_item_GetName( p_item ); TagLib::String *psz_title = new TagLib::String( psz_meta, TagLib::String::UTF8 ); tag->setTitle( *psz_title ); delete psz_title; free( psz_meta ); psz_meta = input_item_GetAlbum( p_item ); SET( Album, psz_meta ); free( psz_meta ); psz_meta = input_item_GetGenre( p_item ); SET( Genre, psz_meta ); free( psz_meta ); psz_meta = input_item_GetDate( p_item ); if( psz_meta ) tag->setYear( atoi( psz_meta ) ); free( psz_meta ); psz_meta = input_item_GetTrackNum( p_item ); if( psz_meta ) tag->setTrack( atoi( psz_meta ) ); free( psz_meta ); f.save(); return VLC_SUCCESS; } msg_Err( p_this, "File %s can't be opened for tag writing\n", p_export->psz_file ); return VLC_EGENERIC; } static int DownloadArt( vlc_object_t *p_this ) { /* We need to be passed the file name * Fetch the thing from the file, save it to the cache folder */ return VLC_EGENERIC; } <commit_msg>Reads more metadata from ID3v2 tags<commit_after>/***************************************************************************** * taglib.cpp: Taglib tag parser/writer ***************************************************************************** * Copyright (C) 2003-2006 the VideoLAN team * $Id$ * * Authors: Clément Stenac <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include <stdlib.h> #include <vlc/vlc.h> #include <vlc_playlist.h> #include <vlc_meta.h> #include <vlc_demux.h> #include <fileref.h> #include <tag.h> #include <tstring.h> #include <id3v2tag.h> #include <mpegfile.h> #include <flacfile.h> #if 0 #include <oggflacfile.h> #endif #include <flacfile.h> #include <flacproperties.h> #include <vorbisfile.h> #include <vorbisproperties.h> #include <uniquefileidentifierframe.h> #include <textidentificationframe.h> //#include <relativevolumeframe.h> /* parse the tags without taglib helpers? */ static int ReadMeta ( vlc_object_t * ); static int DownloadArt ( vlc_object_t * ); static int WriteMeta ( vlc_object_t * ); vlc_module_begin(); set_capability( "meta reader", 1000 ); set_callbacks( ReadMeta, NULL ); add_submodule(); set_capability( "art downloader", 50 ); set_callbacks( DownloadArt, NULL ); add_submodule(); set_capability( "meta writer", 50 ); set_callbacks( WriteMeta, NULL ); vlc_module_end(); static bool checkID3Image( const TagLib::ID3v2::Tag *tag ) { TagLib::ID3v2::FrameList l = tag->frameListMap()[ "APIC" ]; return !l.isEmpty(); } /* Try detecting embedded art */ static void DetectImage( TagLib::FileRef f, vlc_meta_t *p_meta ) { if( TagLib::MPEG::File *mpeg = dynamic_cast<TagLib::MPEG::File *>(f.file() ) ) { if( mpeg->ID3v2Tag() && checkID3Image( mpeg->ID3v2Tag() ) ) vlc_meta_SetArtURL( p_meta, "APIC" ); } else if( TagLib::FLAC::File *flac = dynamic_cast<TagLib::FLAC::File *>(f.file() ) ) { if( flac->ID3v2Tag() && checkID3Image( flac->ID3v2Tag() ) ) vlc_meta_SetArtURL( p_meta, "APIC" ); } #if 0 /* This needs special additions to taglib */ * else if( TagLib::MP4::File *mp4 = dynamic_cast<TagLib::MP4::File *>( f.file() ) ) { TagLib::MP4::Tag *mp4tag = dynamic_cast<TagLib::MP4::Tag *>( mp4->tag() ); if( mp4tag && mp4tag->cover().size() ) vlc_meta_SetArtURL( p_meta, "MP4C" ); } #endif } static int ReadMeta( vlc_object_t *p_this ) { demux_t *p_demux = (demux_t *)p_this; if( !strncmp( p_demux->psz_access, "file", 4 ) ) { if( !p_demux->p_private ) p_demux->p_private = (void*)vlc_meta_New(); TagLib::FileRef f( p_demux->psz_path ); if( !f.isNull() ) { if( TagLib::Ogg::Vorbis::File *p_ogg_v = dynamic_cast<TagLib::Ogg::Vorbis::File *>(f.file() ) ) { int i_ogg_v_length = p_ogg_v->audioProperties()->length(); input_thread_t *p_input = (input_thread_t *)vlc_object_find( p_demux, VLC_OBJECT_INPUT, FIND_PARENT ); if( p_input ) { input_item_t *p_item = input_GetItem( p_input ); if( p_item ) { vlc_mutex_lock( &p_item->lock ); p_item->i_duration = i_ogg_v_length * 1000000; vlc_mutex_unlock( &p_item->lock ); } vlc_object_release( p_input ); } } #if 0 /* at this moment, taglib is unable to detect ogg/flac files * becauses type detection is based on file extension: * ogg = ogg/vorbis * flac = flac * ø = ogg/flac */ else if( TagLib::Ogg::FLAC::File *p_ogg_f = dynamic_cast<TagLib::Ogg::FLAC::File *>(f.file() ) ) { long i_ogg_f_length = p_ogg_f->streamLength(); input_thread_t *p_input = (input_thread_t *)vlc_object_find( p_demux, VLC_OBJECT_INPUT, FIND_PARENT ); if( p_input ) { input_item_t *p_item = input_GetItem( p_input ); if( p_item ) { vlc_mutex_lock( &p_item->lock ); p_item->i_duration = i_ogg_f_length * 1000000; vlc_mutex_unlock( &p_item->lock ); } vlc_object_release( p_input ); } } #endif else if( TagLib::FLAC::File *p_flac = dynamic_cast<TagLib::FLAC::File *>(f.file() ) ) { long i_flac_length = p_flac->audioProperties()->length(); input_thread_t *p_input = (input_thread_t *)vlc_object_find( p_demux, VLC_OBJECT_INPUT, FIND_PARENT ); if( p_input ) { input_item_t *p_item = input_GetItem( p_input ); if( p_item ) { vlc_mutex_lock( &p_item->lock ); p_item->i_duration = i_flac_length * 1000000; vlc_mutex_unlock( &p_item->lock ); } vlc_object_release( p_input ); } } } if( !f.isNull() && f.tag() && !f.tag()->isEmpty() ) { TagLib::Tag *tag = f.tag(); vlc_meta_t *p_meta = (vlc_meta_t *)(p_demux->p_private ); #define SET( foo, bar ) vlc_meta_Set##foo( p_meta, tag->bar ().toCString(true)) #define SETINT( foo, bar ) { \ char psz_tmp[10]; \ snprintf( (char*)psz_tmp, 10, "%d", tag->bar() ); \ vlc_meta_Set##foo( p_meta, (char*)psz_tmp ); \ } SET( Title, title ); SET( Artist, artist ); SET( Album, album ); SET( Description, comment ); SET( Genre, genre ); SETINT( Date, year ); SETINT( Tracknum , track ); #undef SET #undef SETINT if( TagLib::MPEG::File *p_mpeg = dynamic_cast<TagLib::MPEG::File *>(f.file() ) ) { if( p_mpeg->ID3v2Tag() ) { TagLib::ID3v2::Tag *tag = p_mpeg->ID3v2Tag(); TagLib::ID3v2::FrameList list = tag->frameListMap()["UFID"]; TagLib::ID3v2::UniqueFileIdentifierFrame* p_ufid; for( TagLib::ID3v2::FrameList::Iterator iter = list.begin(); iter != list.end(); iter++ ) { p_ufid = dynamic_cast<TagLib::ID3v2::UniqueFileIdentifierFrame*>(*iter); const char *owner = p_ufid->owner().toCString(); if (!strcmp( owner, "http://musicbrainz.org" )) { /* ID3v2 UFID contains up to 64 bytes binary data * but in our case it will be a '\0' * terminated string */ char *psz_ufid = (char*) malloc( 64 ); int j = 0; while( ( j < 63 ) && ( j < p_ufid->identifier().size() ) ) psz_ufid[j] = p_ufid->identifier()[j++]; psz_ufid[j] = '\0'; vlc_meta_SetTrackID( p_meta, psz_ufid ); free( psz_ufid ); } } list = tag->frameListMap()["TXXX"]; TagLib::ID3v2::UserTextIdentificationFrame* p_txxx; for( TagLib::ID3v2::FrameList::Iterator iter = list.begin(); iter != list.end(); iter++ ) { p_txxx = dynamic_cast<TagLib::ID3v2::UserTextIdentificationFrame*>(*iter); const char *psz_desc= p_txxx->description().toCString(); #if 0 /* musicbrainz artist and album id: not useful (yet?) */ if( !strncmp( psz_desc, "MusicBrainz Artist Id", 21 ) ) vlc_meta_SetArtistID( p_meta, p_txxx->fieldList().toString().toCString()); if( !strncmp( psz_desc, "MusicBrainz Album Id", 20 ) ) vlc_meta_SetAlbumID( p_meta, p_txxx->fieldList().toString().toCString()); #endif vlc_meta_AddExtra( p_meta, psz_desc, p_txxx->fieldList().toString().toCString()); } #if 0 list = tag->frameListMap()["RVA2"]; TagLib::ID3v2::RelativeVolumeFrame* p_rva2; for( TagLib::ID3v2::FrameList::Iterator iter = list.begin(); iter != list.end(); iter++ ) { p_rva2 = dynamic_cast<TagLib::ID3v2::RelativeVolumeFrame*>(*iter); /* TODO: process rva2 frames */ } #endif list = tag->frameList(); TagLib::ID3v2::Frame* p_t; char psz_tag[4]; for( TagLib::ID3v2::FrameList::Iterator iter = list.begin(); iter != list.end(); iter++ ) { p_t = dynamic_cast<TagLib::ID3v2::Frame*> (*iter); memcpy( psz_tag, p_t->frameID().data(), 4); #define SET( foo, bar ) if( !strncmp( psz_tag, foo, 4 ) ) \ vlc_meta_Set##bar( p_meta, p_t->toString().toCString(true)) SET( "TPUB", Publisher ); SET( "TCOP", Copyright ); SET( "TENC", EncodedBy ); SET( "TLAN", Language ); //SET( "POPM", Rating ); //if( !strncmp( psz_tag, "RVA2", 4 ) ) /* TODO */ #undef SET } } } DetectImage( f, p_meta ); return VLC_SUCCESS; } } return VLC_EGENERIC; } #define SET(a,b) if(b) { \ TagLib::String *psz_##a = new TagLib::String( b, \ TagLib::String::UTF8 ); \ tag->set##a( *psz_##a ); \ delete psz_##a; \ } static int WriteMeta( vlc_object_t *p_this ) { playlist_t *p_playlist = (playlist_t *)p_this; meta_export_t *p_export = (meta_export_t *)p_playlist->p_private; input_item_t *p_item = p_export->p_item; if( p_item == NULL ) { msg_Err( p_this, "Can't save meta data of an empty input" ); return VLC_EGENERIC; } TagLib::FileRef f( p_export->psz_file ); if( !f.isNull() && f.tag() ) { msg_Dbg( p_this, "Updating metadata for %s", p_export->psz_file ); TagLib::Tag *tag = f.tag(); char *psz_meta; psz_meta = input_item_GetArtist( p_item ); SET( Artist, psz_meta ); free( psz_meta ); psz_meta = input_item_GetTitle( p_item ); if( !psz_meta ) psz_meta = input_item_GetName( p_item ); TagLib::String *psz_title = new TagLib::String( psz_meta, TagLib::String::UTF8 ); tag->setTitle( *psz_title ); delete psz_title; free( psz_meta ); psz_meta = input_item_GetAlbum( p_item ); SET( Album, psz_meta ); free( psz_meta ); psz_meta = input_item_GetGenre( p_item ); SET( Genre, psz_meta ); free( psz_meta ); psz_meta = input_item_GetDate( p_item ); if( psz_meta ) tag->setYear( atoi( psz_meta ) ); free( psz_meta ); psz_meta = input_item_GetTrackNum( p_item ); if( psz_meta ) tag->setTrack( atoi( psz_meta ) ); free( psz_meta ); f.save(); return VLC_SUCCESS; } msg_Err( p_this, "File %s can't be opened for tag writing\n", p_export->psz_file ); return VLC_EGENERIC; } static int DownloadArt( vlc_object_t *p_this ) { /* We need to be passed the file name * Fetch the thing from the file, save it to the cache folder */ return VLC_EGENERIC; } <|endoftext|>
<commit_before>#ifndef CLOTHO_VARIABLE_SUBSET_RECOMBINATION_DEF_HPP_ #define CLOTHO_VARIABLE_SUBSET_RECOMBINATION_DEF_HPP_ #include "clotho/powerset/config.hpp" #include <iostream> #include <cassert> #include <algorithm> #include "clotho/recombination/recombination_def.hpp" #include "clotho/powerset/variable_subset.hpp" #include "clotho/utility/bit_walker.hpp" namespace clotho { namespace recombine { template < class Element, class Block, class BlockMap, class ElementKeyer, class Classifier > class recombination< clotho::powersets::variable_subset< Element, Block, BlockMap, ElementKeyer >, Classifier > { public: typedef clotho::powersets::variable_subset< Element, Block, BlockMap, ElementKeyer > subset_type; typedef typename subset_type::pointer sequence_type; typedef Classifier classifier_type; typedef typename subset_type::bitset_type bit_sequence_type; typedef Block block_type; typedef clotho::utility::block_walker< block_type, unsigned short > block_walker_type; void operator()( sequence_type base, sequence_type alt, classifier_type & elem_classifier) { m_match_base = m_match_alt = m_empty = true; m_res_seq.reset(); if( base == alt ) { // pointers match if( base ) { m_empty = false; m_res_seq.resize( base->max_size(), false); std::copy( base->begin(), base->end(), m_res_seq.m_bits.begin() ); } return; } typename subset_type::cblock_iterator base_it, base_end; typename subset_type::cblock_iterator alt_it, alt_end; if( !base ) { // base sequence is empty // NOTE: since base != alt, alt must be defined alt_it = alt->begin(); alt_end = alt->end(); // slight "trick" to cause following loop to iterate only // over the alt sequence base_it = alt->end(); base_end = alt->end(); m_res_seq.resize( alt->max_size(), false ); } else if( !alt ) { // alt sequence is empty base_it = base->begin(); base_end = base->end(); // slight "trick" to cause following loop to iterate only // over the base sequence alt_it = base->end(); alt_end = base->end(); m_res_seq.resize( base->max_size(), false ); } else { assert( base->isSameFamily( alt ) ); base_it = base->begin(); base_end = base->end(); alt_it = alt->begin(); alt_end = alt->end(); m_res_seq.resize( base->max_size(), false ); } typename subset_type::block_iterator res_it = m_res_seq.m_bits.begin(); while( true ) { if( alt_it == alt_end ) { while( base_it != base_end ) { block_type _base = (*base_it++); recombine( (*res_it), _base, 0, elem_classifier ); if( base_it != base_end ) { ++res_it; elem_classifier.updateOffset( block_walker_type::bits_per_block ); } else { break; } } break; } if( base_it == base_end ) { while( alt_it != alt_end ) { block_type _alt = (*alt_it++); recombine( (*res_it), 0, _alt, elem_classifier ); if( alt_it != alt_end ) { ++res_it; elem_classifier.updateOffset( block_walker_type::bits_per_block ); } else { break; } } break; } block_type _base = (*base_it++), _alt = (*alt_it++); recombine( (*res_it), _base, _alt, elem_classifier ); ++res_it; elem_classifier.updateOffset( block_walker_type::bits_per_block ); } } bit_sequence_type * getResultSequence() { return &m_res_seq; } bool isMatchBase() const { return m_match_base; } bool isMatchAlt() const { return m_match_alt; } bool isEmpty() const { return m_empty; } void recombine( block_type & res, const block_type base, const block_type alt, classifier_type & elem_classifier ) { block_type hom = base & alt; block_type hets = base ^ alt; elem_classifier.resetResult(); block_walker_type::apply( hets, elem_classifier ); block_type base_mask = elem_classifier.getResult(); block_type alt_mask = ((~base_mask & hets) & alt); res =(hom | (alt_mask | (base_mask & base))); m_match_base = (m_match_base && (base == res) ); m_match_alt = (m_match_alt && (alt == res) ); m_empty = (m_empty && (res == 0) ); } virtual ~recombination() {} protected: bit_sequence_type m_res_seq; bool m_match_base, m_match_alt, m_empty; }; } // namespace recombine } // namespace clotho #endif // CLOTHO_VARIABLE_SUBSET_RECOMBINATION_DEF_HPP_ <commit_msg>Modified to make use of newly created bit_block_recombiner and classifiers<commit_after>#ifndef CLOTHO_VARIABLE_SUBSET_RECOMBINATION_DEF_HPP_ #define CLOTHO_VARIABLE_SUBSET_RECOMBINATION_DEF_HPP_ #include "clotho/powerset/config.hpp" #include <iostream> #include <cassert> #include <algorithm> #include "clotho/recombination/recombination_def.hpp" #include "clotho/recombination/bit_block_recombiner.hpp" #include "clotho/powerset/variable_subset.hpp" namespace clotho { namespace recombine { template < class Element, class Block, class BlockMap, class ElementKeyer, class Classifier > class recombination< clotho::powersets::variable_subset< Element, Block, BlockMap, ElementKeyer >, Classifier > { public: typedef clotho::powersets::variable_subset< Element, Block, BlockMap, ElementKeyer > subset_type; typedef typename subset_type::pointer sequence_type; typedef Classifier classifier_type; typedef clotho::recombine::bit_block_recombiner< Classifier > recombiner_type; typedef typename subset_type::bitset_type bit_sequence_type; typedef Block block_type; static const unsigned int bits_per_block = sizeof( block_type ) * 8; void operator()( sequence_type base, sequence_type alt, classifier_type & elem_classifier ) { m_match_base = m_match_alt = m_empty = true; m_res_seq.reset(); if( base == alt ) { // pointers match if( base ) { m_empty = false; m_res_seq.resize( base->max_size(), false); std::copy( base->begin(), base->end(), m_res_seq.m_bits.begin() ); } return; } typename subset_type::cblock_iterator base_it, base_end; typename subset_type::cblock_iterator alt_it, alt_end; typename subset_type::powerset_type::cvariable_iterator elem_it; if( !base ) { // base sequence is empty // NOTE: since base != alt, alt must be defined alt_it = alt->begin(); alt_end = alt->end(); // slight "trick" to cause following loop to iterate only // over the alt sequence base_it = alt->end(); base_end = alt->end(); elem_it = alt->getParent()->variable_begin(); m_res_seq.resize( alt->max_size(), false ); } else if( !alt ) { // alt sequence is empty base_it = base->begin(); base_end = base->end(); // slight "trick" to cause following loop to iterate only // over the base sequence alt_it = base->end(); alt_end = base->end(); elem_it = base->getParent()->variable_begin(); m_res_seq.resize( base->max_size(), false ); } else { assert( base->isSameFamily( alt ) ); base_it = base->begin(); base_end = base->end(); alt_it = alt->begin(); alt_end = alt->end(); elem_it = base->getParent()->variable_begin(); m_res_seq.resize( base->max_size(), false ); } typename subset_type::block_iterator res_it = m_res_seq.m_bits.begin(); recombiner_type brecombiner( elem_classifier ); while( true ) { if( alt_it == alt_end ) { while( base_it != base_end ) { block_type _base = (*base_it++); block_type r = brecombiner( _base, (block_type)0, elem_it ); m_match_base = (m_match_base && (_base == r) ); m_match_alt = (m_match_alt && ((block_type)0 == r) ); m_empty = (m_empty && (r == (block_type)0) ); (*res_it++) = r; elem_it += bits_per_block; } break; } if( base_it == base_end ) { while( alt_it != alt_end ) { block_type _alt = (*alt_it++); block_type r = brecombiner( (block_type)0, _alt, elem_it ); m_match_base = (m_match_base && ((block_type)0 == r) ); m_match_alt = (m_match_alt && (_alt == r) ); m_empty = (m_empty && (r == (block_type)0) ); (*res_it++) = r; elem_it += bits_per_block; } break; } block_type _base = (*base_it++), _alt = (*alt_it++); block_type r = brecombiner( _base, _alt, elem_it ); m_match_base = (m_match_base && (_base == r) ); m_match_alt = (m_match_alt && (_alt == r) ); m_empty = (m_empty && (r == 0) ); (*res_it++) = r; elem_it += bits_per_block; } } bit_sequence_type * getResultSequence() { return &m_res_seq; } bool isMatchBase() const { return m_match_base; } bool isMatchAlt() const { return m_match_alt; } bool isEmpty() const { return m_empty; } virtual ~recombination() {} protected: bit_sequence_type m_res_seq; bool m_match_base, m_match_alt, m_empty; }; } // namespace recombine } // namespace clotho #endif // CLOTHO_VARIABLE_SUBSET_RECOMBINATION_DEF_HPP_ <|endoftext|>
<commit_before>/* Copyright (c) 2017, Vadim Malyshev, [email protected] All rights reserved */ #include "stdafx.h" #include "get_root_app.h" #include "keys_control.h" vds::get_root_app::get_root_app() : key_generate_command_set_("Generate keys", "Generate keys", "generate", "keys"), user_login_( "l", "login", "Login", "User login"), user_password_( "p", "password", "Password", "User password") { } void out_multiline(const std::string & value, std::size_t width = 80) { for(std::size_t pos = 0; pos < value.length();) { if(value.length() > pos + width) { std::cout << "\"" << value.substr(pos, width) << "\"\n"; pos += width; } else { std::cout << "\"" << value.substr(pos) << "\""; break; } } } #define write_member(member_name)\ std::cout << "char vds::keys_control::" #member_name "[" \ << sizeof(keys_control::member_name) \ << "] = \n";\ out_multiline(keys_control::member_name);\ std::cout << ";\n"; vds::expected<void> vds::get_root_app::main(const service_provider * /*sp*/) { if (&this->key_generate_command_set_ == this->current_command_set_) { keys_control::private_info_t private_info; CHECK_EXPECTED(private_info.genereate_all()); CHECK_EXPECTED(keys_control::genereate_all( private_info)); write_member(root_id_); write_member(common_news_channel_id_); write_member(common_news_read_public_key_); write_member(common_news_read_private_key_); write_member(common_news_write_public_key_); write_member(common_news_admin_public_key_); write_member(autoupdate_channel_id_); write_member(autoupdate_read_public_key_); write_member(autoupdate_read_private_key_); write_member(autoupdate_write_public_key_); write_member(autoupdate_admin_public_key_); write_member(web_channel_id_); write_member(web_read_public_key_); write_member(web_read_private_key_); write_member(web_write_public_key_); write_member(web_admin_public_key_); binary_serializer s; CHECK_EXPECTED(s << private_info.root_private_key_->der(this->user_password_.value())); CHECK_EXPECTED(s << private_info.common_news_write_private_key_->der(this->user_password_.value())); CHECK_EXPECTED(s << private_info.common_news_admin_private_key_->der(this->user_password_.value())); CHECK_EXPECTED(s << private_info.autoupdate_write_private_key_->der(this->user_password_.value())); CHECK_EXPECTED(s << private_info.autoupdate_admin_private_key_->der(this->user_password_.value())); CHECK_EXPECTED(s << private_info.web_write_private_key_->der(this->user_password_.value())); CHECK_EXPECTED(s << private_info.web_admin_private_key_->der(this->user_password_.value())); CHECK_EXPECTED(file::write_all(filename("keys"), s.move_data())); } return expected<void>(); } void vds::get_root_app::register_services(vds::service_registrator& registrator) { base_class::register_services(registrator); registrator.add(this->mt_service_); registrator.add(this->task_manager_); registrator.add(this->crypto_service_); } void vds::get_root_app::register_command_line(command_line & cmd_line) { base_class::register_command_line(cmd_line); cmd_line.add_command_set(this->key_generate_command_set_); this->key_generate_command_set_.required(this->user_login_); this->key_generate_command_set_.required(this->user_password_); } vds::expected<void> vds::get_root_app::start_services(service_registrator & registrator, service_provider * sp) { return base_class::start_services(registrator, sp); } <commit_msg>update<commit_after>/* Copyright (c) 2017, Vadim Malyshev, [email protected] All rights reserved */ #include "stdafx.h" #include "get_root_app.h" #include "keys_control.h" vds::get_root_app::get_root_app() : key_generate_command_set_("Generate keys", "Generate keys", "generate", "keys"), user_login_( "l", "login", "Login", "User login"), user_password_( "p", "password", "Password", "User password") { } void out_multiline(const std::string & value, std::size_t width = 80) { for(std::size_t pos = 0; pos < value.length();) { if(value.length() > pos + width) { std::cout << "\"" << value.substr(pos, width) << "\"\n"; pos += width; } else { std::cout << "\"" << value.substr(pos) << "\""; break; } } } #define write_member(member_name)\ std::cout << "char vds::keys_control::" #member_name "[" \ << sizeof(keys_control::member_name) \ << "] = \n";\ out_multiline(keys_control::member_name);\ std::cout << ";\n"; vds::expected<void> vds::get_root_app::main(const service_provider * /*sp*/) { if (&this->key_generate_command_set_ == this->current_command_set_) { keys_control::private_info_t private_info; CHECK_EXPECTED(private_info.genereate_all()); CHECK_EXPECTED(keys_control::genereate_all( private_info)); write_member(root_id_); binary_serializer s; CHECK_EXPECTED(s << private_info.root_private_key_->der(this->user_password_.value())); CHECK_EXPECTED(file::write_all(filename("keys"), s.move_data())); } return expected<void>(); } void vds::get_root_app::register_services(vds::service_registrator& registrator) { base_class::register_services(registrator); registrator.add(this->mt_service_); registrator.add(this->task_manager_); registrator.add(this->crypto_service_); } void vds::get_root_app::register_command_line(command_line & cmd_line) { base_class::register_command_line(cmd_line); cmd_line.add_command_set(this->key_generate_command_set_); this->key_generate_command_set_.required(this->user_login_); this->key_generate_command_set_.required(this->user_password_); } vds::expected<void> vds::get_root_app::start_services(service_registrator & registrator, service_provider * sp) { return base_class::start_services(registrator, sp); } <|endoftext|>
<commit_before>/** * \file * \brief StaticSignalInformationQueueWrapper class header * * \author Copyright (C) 2015 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/. * * \date 2015-03-26 */ #ifndef INCLUDE_DISTORTOS_STATICSIGNALINFORMATIONQUEUEWRAPPER_HPP_ #define INCLUDE_DISTORTOS_STATICSIGNALINFORMATIONQUEUEWRAPPER_HPP_ #include "distortos/SignalInformationQueueWrapper.hpp" namespace distortos { /** * \brief StaticSignalInformationQueueWrapper class is a variant of SignalInformationQueueWrapper that has automatic * storage for queue's contents. * * \param QueueSize is the maximum number of elements in queue */ template<size_t QueueSize> class StaticSignalInformationQueueWrapper : public SignalInformationQueueWrapper { public: /** * \brief StaticSignalInformationQueueWrapper's constructor */ StaticSignalInformationQueueWrapper() : SignalInformationQueueWrapper{storage_} { } private: /// storage for queue's contents std::array<Storage, QueueSize> storage_; }; } // namespace distortos #endif // INCLUDE_DISTORTOS_STATICSIGNALINFORMATIONQUEUEWRAPPER_HPP_ <commit_msg>remove StaticSignalInformationQueueWrapper.hpp<commit_after><|endoftext|>
<commit_before>#ifndef EBITEN_GRAPHICS_DETAIL_OPENGL_IOS_NATIVE_VIEW_HPP #define EBITEN_GRAPHICS_DETAIL_OPENGL_IOS_NATIVE_VIEW_HPP #include "ebiten/input.hpp" namespace ebiten { namespace graphics { namespace detail { typedef GLKView* native_view; namespace { void native_view_set_input(native_view nv, class input& input) { // TODO: implement EbitenGLKViewDelegate* delegate = nv.delegate; [delegate setInput:input]; } } } } } #endif <commit_msg>Implemented for iOS<commit_after>#ifndef EBITEN_GRAPHICS_DETAIL_OPENGL_IOS_NATIVE_VIEW_HPP #define EBITEN_GRAPHICS_DETAIL_OPENGL_IOS_NATIVE_VIEW_HPP #include "ebiten/input.hpp" namespace ebiten { namespace graphics { namespace detail { typedef GLKView* native_view; namespace { void native_view_set_input(native_view nv, class input& input) { // TODO: implement EbitenGLKViewDelegate* delegate = nv.delegate; [delegate setInput:input]; } bool native_view_is_terminated(native_view) { return false; } } } } } #endif <|endoftext|>
<commit_before>/********************************************************************************* * Copyright (c) 2013 David D. Marshall <[email protected]> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Rob McDonald - implementation of binary cubic creator ********************************************************************************/ #ifndef eli_geom_curve_piecewise_binary_cubic_creator_hpp #define eli_geom_curve_piecewise_binary_cubic_creator_hpp #include <iterator> #include <vector> #include "eli/code_eli.hpp" #include "eli/geom/curve/piecewise.hpp" #include "eli/geom/curve/bezier.hpp" #include "eli/geom/point/distance.hpp" namespace eli { namespace geom { namespace curve { template<typename data__, unsigned short dim__, typename tol__> class piecewise_binary_cubic_creator { public: typedef data__ data_type; typedef Eigen::Matrix<data_type, 1, dim__> point_type; typedef typename point_type::Index index_type; typedef tol__ tolerance_type; typedef piecewise<bezier, data_type, dim__, tolerance_type> piecewise_curve_type; typedef typename piecewise_curve_type::curve_type curve_type; piecewise_binary_cubic_creator() {} void setup(const piecewise_curve_type &pc, const data_type &t, const index_type &dmin, const index_type &dmax) { parent_curve = pc; parent_curve.get_pmap( parent_pmap ); ttol = t; min_depth = dmin; max_depth = dmax; } virtual bool create(piecewise<bezier, data_type, dim__, tolerance_type> &pc) const { typedef typename piecewise_curve_type::error_code error_code; data_type t0, t1; t0 = parent_curve.get_t0(); t1 = parent_curve.get_tmax(); point_type p0, m0, p1, m1; p0 = parent_curve.f(t0); m0 = parent_curve.fp(t0); p1 = parent_curve.f(t1); m1 = parent_curve.fp(t1); pc.clear(); // set the start parameter pc.set_t0( t0 ); // Build approximate curve. curve_type c; c = make_curve_point_slope(p0, m0, p1, m1, t1-t0); pc.push_back(c, t1-t0); adapt_pc( pc, t0, p0, m0, t1, p1, m1); return true; } protected: void adapt_pc( piecewise<bezier, data_type, dim__, tolerance_type> &pc, const data_type &t0, const point_type &p0, const point_type &m0, const data_type &t1, const point_type &p1, const point_type &m1, index_type depth = 0 ) const { data_type tmid = ( t0 + t1 ) / 2.0; point_type pmid = parent_curve.f( tmid ); bool adapt = false; if ( depth < min_depth ) { adapt = true; } else if ( eli::geom::point::distance( pmid, pc.f( tmid ) ) > ttol ) { adapt = true; } else if ( !test_match( pc, t0, t1 ) ) { adapt = true; } if ( adapt && depth < max_depth ) { point_type mmid = parent_curve.fp( tmid ); piecewise<bezier, data_type, dim__, tolerance_type> insert; insert.set_t0( t0 ); curve_type c1; c1 = make_curve_point_slope(p0, m0, pmid, mmid, tmid-t0); insert.push_back(c1, tmid-t0); curve_type c2; c2 = make_curve_point_slope(pmid, mmid, p1, m1, t1-tmid); insert.push_back(c2, t1-tmid); pc.replace_t( insert, t0 ); adapt_pc( pc, t0, p0, m0, tmid, pmid, mmid, depth + 1 ); adapt_pc( pc, tmid, pmid, mmid, t1, p1, m1, depth + 1 ); } } bool test_match( const piecewise<bezier, data_type, dim__, tolerance_type> &pc, const data_type &tstart, const data_type &tend ) const { data_type tcheck; // Check start/end and midpoints of piecewise parent curve that overlap range. for ( typename std::vector< data_type>::size_type i = 0; i < parent_pmap.size() - 1; i++ ) { if ( parent_pmap[ i ] <= tend && parent_pmap[ i + 1 ] >= tstart ) { tcheck = parent_pmap[ i ]; if ( tcheck >= tstart && tcheck <= tend ) { if ( eli::geom::point::distance( parent_curve.f( tcheck ), pc.f( tcheck ) ) > ttol ) { return false; } } tcheck = ( parent_pmap[ i ] + parent_pmap[ i + 1 ] ) / 2.0; if ( tcheck >= tstart && tcheck <= tend ) { if ( eli::geom::point::distance( parent_curve.f( tcheck ), pc.f( tcheck ) ) > ttol ) { return false; } } } } return true; } static curve_type make_curve_point_slope(const point_type &p0, const point_type &m0, const point_type &p1, const point_type &m1, const data_type &dt) { curve_type c(3); point_type cp[4]; cp[0]=p0; cp[1]=p0+(dt*m0/3.0); cp[2]=p1-(dt*m1/3.0); cp[3]=p1; for (index_type i=0; i<4; ++i) { c.set_control_point(cp[i], i); } return c; } private: piecewise_curve_type parent_curve; std::vector < data_type > parent_pmap; data_type ttol; index_type min_depth; index_type max_depth; }; } } } #endif <commit_msg>Add piecewise binary cubic creator to detect and honor corners in curves.<commit_after>/********************************************************************************* * Copyright (c) 2013 David D. Marshall <[email protected]> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Rob McDonald - implementation of binary cubic creator ********************************************************************************/ #ifndef eli_geom_curve_piecewise_binary_cubic_creator_hpp #define eli_geom_curve_piecewise_binary_cubic_creator_hpp #include <iterator> #include <vector> #include "eli/code_eli.hpp" #include "eli/geom/curve/piecewise.hpp" #include "eli/geom/curve/bezier.hpp" #include "eli/geom/point/distance.hpp" namespace eli { namespace geom { namespace curve { template<typename data__, unsigned short dim__, typename tol__> class piecewise_binary_cubic_creator { public: typedef data__ data_type; typedef Eigen::Matrix<data_type, 1, dim__> point_type; typedef typename point_type::Index index_type; typedef tol__ tolerance_type; typedef piecewise<bezier, data_type, dim__, tolerance_type> piecewise_curve_type; typedef typename piecewise_curve_type::curve_type curve_type; piecewise_binary_cubic_creator() {} void setup(const piecewise_curve_type &pc, const data_type &t, const index_type &dmin, const index_type &dmax) { parent_curve = pc; parent_curve.get_pmap( parent_pmap ); ttol = t; atol = -1.0; min_depth = dmin; max_depth = dmax; } void setup(const piecewise_curve_type &pc, const data_type &t, const data_type &a, const index_type &dmin, const index_type &dmax) { setup( pc, t, dmin, dmax ); atol = a; } virtual bool corner_create(piecewise<bezier, data_type, dim__, tolerance_type> &pc) const { std::vector<data_type> tdisc; point_type p0, m01, m02, p1, m11, m12; parent_curve.find_discontinuities( atol, tdisc ); data_type t0, tmax, t1; t0 = parent_curve.get_t0(); tmax = parent_curve.get_tmax(); tdisc.push_back( tmax ); pc.clear(); // set the start parameter pc.set_t0( t0 ); p0 = parent_curve.f(t0); parent_curve.fps(t0, m01, m02); for ( typename std::vector< data_type>::size_type i = 0; i < tdisc.size(); i++ ) { t1 = tdisc[i]; p1 = parent_curve.f(t1); parent_curve.fps(t1, m11, m12); // Build approximate curve. curve_type c; c = make_curve_point_slope(p0, m02, p1, m11, t1-t0); pc.push_back(c, t1-t0); adapt_pc( pc, t0, p0, m02, t1, p1, m11); t0 = t1; p0 = p1; m01 = m11; m02 = m12; } return true; } virtual bool create(piecewise<bezier, data_type, dim__, tolerance_type> &pc) const { typedef typename piecewise_curve_type::error_code error_code; data_type t0, t1; t0 = parent_curve.get_t0(); t1 = parent_curve.get_tmax(); point_type p0, m0, p1, m1; p0 = parent_curve.f(t0); m0 = parent_curve.fp(t0); p1 = parent_curve.f(t1); m1 = parent_curve.fp(t1); pc.clear(); // set the start parameter pc.set_t0( t0 ); // Build approximate curve. curve_type c; c = make_curve_point_slope(p0, m0, p1, m1, t1-t0); pc.push_back(c, t1-t0); adapt_pc( pc, t0, p0, m0, t1, p1, m1); return true; } protected: void adapt_pc( piecewise<bezier, data_type, dim__, tolerance_type> &pc, const data_type &t0, const point_type &p0, const point_type &m0, const data_type &t1, const point_type &p1, const point_type &m1, index_type depth = 0 ) const { data_type tmid = ( t0 + t1 ) / 2.0; point_type pmid = parent_curve.f( tmid ); bool adapt = false; if ( depth < min_depth ) { adapt = true; } else if ( eli::geom::point::distance( pmid, pc.f( tmid ) ) > ttol ) { adapt = true; } else if ( !test_match( pc, t0, t1 ) ) { adapt = true; } if ( adapt && depth < max_depth ) { point_type mmid = parent_curve.fp( tmid ); piecewise<bezier, data_type, dim__, tolerance_type> insert; insert.set_t0( t0 ); curve_type c1; c1 = make_curve_point_slope(p0, m0, pmid, mmid, tmid-t0); insert.push_back(c1, tmid-t0); curve_type c2; c2 = make_curve_point_slope(pmid, mmid, p1, m1, t1-tmid); insert.push_back(c2, t1-tmid); pc.replace_t( insert, t0 ); adapt_pc( pc, t0, p0, m0, tmid, pmid, mmid, depth + 1 ); adapt_pc( pc, tmid, pmid, mmid, t1, p1, m1, depth + 1 ); } } bool test_match( const piecewise<bezier, data_type, dim__, tolerance_type> &pc, const data_type &tstart, const data_type &tend ) const { data_type tcheck; // Check start/end and midpoints of piecewise parent curve that overlap range. for ( typename std::vector< data_type>::size_type i = 0; i < parent_pmap.size() - 1; i++ ) { if ( parent_pmap[ i ] <= tend && parent_pmap[ i + 1 ] >= tstart ) { tcheck = parent_pmap[ i ]; if ( tcheck >= tstart && tcheck <= tend ) { if ( eli::geom::point::distance( parent_curve.f( tcheck ), pc.f( tcheck ) ) > ttol ) { return false; } } tcheck = ( parent_pmap[ i ] + parent_pmap[ i + 1 ] ) / 2.0; if ( tcheck >= tstart && tcheck <= tend ) { if ( eli::geom::point::distance( parent_curve.f( tcheck ), pc.f( tcheck ) ) > ttol ) { return false; } } } } return true; } static curve_type make_curve_point_slope(const point_type &p0, const point_type &m0, const point_type &p1, const point_type &m1, const data_type &dt) { curve_type c(3); point_type cp[4]; cp[0]=p0; cp[1]=p0+(dt*m0/3.0); cp[2]=p1-(dt*m1/3.0); cp[3]=p1; for (index_type i=0; i<4; ++i) { c.set_control_point(cp[i], i); } return c; } private: piecewise_curve_type parent_curve; std::vector < data_type > parent_pmap; data_type ttol; data_type atol; index_type min_depth; index_type max_depth; }; } } } #endif <|endoftext|>
<commit_before>// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2022 Antti Nuortimo. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #include "entity.hpp" #include "variable.hpp" #include "universe.hpp" #include "family_templates.hpp" #include "entity_factory.hpp" #include "entity_variable_activation.hpp" #include "entity_variable_read.hpp" #include "entity_struct.hpp" #include "variable_struct.hpp" #include "code/ylikuutio/data/any_value.hpp" // Include standard headers #include <cstddef> // std::size_t #include <regex> // std::regex, std::regex_match #include <string> // std::string namespace yli::ontology { class Scene; void Entity::bind_variable(yli::ontology::Variable* const variable) { if (variable != nullptr) { this->parent_of_variables.bind_child(variable); // `variable` with a local name needs to be added to `entity_map` as well. this->add_entity(variable->get_local_name(), variable); } } void Entity::unbind_variable(const std::size_t childID) { this->parent_of_variables.unbind_child(childID); } void Entity::bind_to_universe() { // Requirements: // `this->universe` must not be `nullptr`. yli::ontology::Universe* const universe = this->universe; if (universe == nullptr) { // When `Application` is created, `universe` is still `nullptr`. return; } // Get `entityID` from the `Universe` and set pointer to this `Entity`. universe->bind_entity(this); } void Entity::bind_to_new_parent(yli::ontology::Entity* /* new_parent */) { // Do nothing. // `yli::ontology` classes which support binding must `override` // this `yli::ontology::Entity` base class implementation. } Entity::Entity(yli::ontology::Universe* const universe, const yli::ontology::EntityStruct& entity_struct) : registry(), parent_of_variables(this, &this->registry, ""), // Do not index `parent_of_variables`, index only the variables. parent_of_any_struct_entities(this, &this->registry, "any_struct_entities"), universe { universe }, is_variable { entity_struct.is_variable } { // constructor. // Get `entityID` from `Universe` and set pointer to this `Entity`. this->bind_to_universe(); if (!this->is_variable && this->universe != nullptr && this->universe != this) { this->should_be_rendered = !this->universe->get_is_headless(); yli::ontology::VariableStruct should_be_rendered_variable_struct; should_be_rendered_variable_struct.local_name = "should_be_rendered"; should_be_rendered_variable_struct.activate_callback = &yli::ontology::activate_should_be_rendered; should_be_rendered_variable_struct.read_callback = &yli::ontology::read_should_be_rendered; should_be_rendered_variable_struct.should_call_activate_callback_now = true; this->create_variable(should_be_rendered_variable_struct, yli::data::AnyValue(this->should_be_rendered)); } } Entity::~Entity() { // destructor. if (this->universe == nullptr) { // When leaving the `main` before binding `Application` to `Universe`, // `this->universe` is still `nullptr`. return; } this->universe->unbind_entity(this->entityID); if (!this->global_name.empty() && this->universe != nullptr) { // OK, this `Entity` had a global name, so it's global name shall be erased. this->universe->erase_entity(this->global_name); } // Local names must be erased in the destructors // of classes that inherit `yli::ontology::Entity`! // They can not be erased here in `Entity` destructor, // because `Entity` class does not keep track of the // parent. `Entity` only provides virtual function // `Entity::get_parent`, but that can not be called // from here. } void Entity::activate() { } std::size_t Entity::get_childID() const { return this->childID; } std::string Entity::get_type() const { return this->type_string; } bool Entity::get_can_be_erased() const { return this->can_be_erased; } yli::ontology::Universe* Entity::get_universe() const { return this->universe; } yli::ontology::EntityFactory* Entity::get_entity_factory() const { if (this->universe == nullptr) { return nullptr; } return this->universe->get_entity_factory(); } bool Entity::has_child(const std::string& name) const { return this->registry.is_entity(name); } yli::ontology::Entity* Entity::get_entity(const std::string& name) const { // Requirements: // `name` must not begin with a dot. // `name` must not end with a dot. std::size_t first_dot_pos = name.find_first_of('.'); if (first_dot_pos == std::string::npos) { // There are no dots in the name. if (!this->registry.is_entity(name)) { return nullptr; } return this->registry.get_entity(name); } // OK, assumedly we have a multi-part name. const std::string first = std::string(name, 0, first_dot_pos); const std::string rest = std::string(name, ++first_dot_pos); if (first.empty()) { // Name must not be empty. return nullptr; } if (!this->registry.is_entity(first)) { return nullptr; } yli::ontology::Entity* entity = this->registry.get_entity(first); if (entity == nullptr) { return nullptr; } return entity->get_entity(rest); } std::string Entity::get_entity_names() const { return this->registry.get_entity_names(); } void Entity::add_entity(const std::string& name, yli::ontology::Entity* const entity) { this->registry.add_entity(entity, name); } void Entity::erase_entity(const std::string& name) { this->registry.erase_entity(name); } void Entity::create_variable(const yli::ontology::VariableStruct& variable_struct, const yli::data::AnyValue& any_value) { if (this->universe == nullptr) { return; } yli::ontology::EntityFactory* const entity_factory = this->universe->get_entity_factory(); if (entity_factory == nullptr) { return; } yli::ontology::VariableStruct new_variable_struct(variable_struct); new_variable_struct.parent = this; entity_factory->create_variable(new_variable_struct, any_value); } bool Entity::has_variable(const std::string& variable_name) const { return this->get(variable_name) != nullptr; } yli::ontology::Variable* Entity::get(const std::string& variable_name) const { return dynamic_cast<yli::ontology::Variable*>(this->registry.get_entity(variable_name)); } bool Entity::set(const std::string& variable_name, const yli::data::AnyValue& variable_new_any_value) { yli::ontology::Variable* const variable = this->get(variable_name); if (variable == nullptr) { return false; } // OK, this is a valid variable name. // Set the variable value and activate it by // calling the corresponding activate callback. variable->set(variable_new_any_value); return true; } std::string Entity::help() const { std::string help_string = "TODO: create general helptext"; return help_string; } std::string Entity::help(const std::string& variable_name) const { yli::ontology::Variable* const variable = this->get(variable_name); if (variable == nullptr) { return this->help(); } return variable->help(); } void Entity::prerender() const { // Requirements: // `this->prerender_callback` must not be `nullptr`. // `this->universe` must not be `nullptr`. if (this->prerender_callback != nullptr && this->universe != nullptr) { this->prerender_callback(this->universe); } } void Entity::postrender() const { // Requirements: // `this->postrender_callback` must not be `nullptr`. // `this->universe` must not be `nullptr`. if (this->postrender_callback != nullptr && this->universe != nullptr) { this->postrender_callback(this->universe); } } std::string Entity::get_global_name() const { return this->global_name; } std::size_t Entity::get_number_of_all_children() const { return this->parent_of_variables.get_number_of_children() + this->get_number_of_non_variable_children(); } std::size_t Entity::get_number_of_all_descendants() const { return yli::ontology::get_number_of_descendants(this->parent_of_variables.child_pointer_vector) + yli::ontology::get_number_of_descendants(this->parent_of_any_struct_entities.child_pointer_vector) + this->get_number_of_descendants(); } std::size_t Entity::get_number_of_variables() const { return this->parent_of_variables.get_number_of_children(); } std::size_t Entity::get_number_of_non_variable_children() const { return this->parent_of_any_struct_entities.get_number_of_children() + this->get_number_of_children(); } std::string Entity::get_local_name() const { return this->local_name; } void Entity::set_global_name(const std::string& global_name) { // Requirements: // `this->universe` must not be `nullptr`. // `global_name` must not be already in use. if (global_name.empty()) { return; } if (!std::regex_match(global_name, std::regex("[a-zA-Z][a-zA-Z0-9_-]*"))) { return; } if (this->universe == nullptr) { return; } if (this->universe->has_child(global_name)) { // The global name is already in use. return; } // Erase old global name. this->universe->erase_entity(this->global_name); // Set new global name. this->global_name = global_name; this->universe->add_entity(global_name, this); if (this->universe == this->get_parent()) { // `Universe` is the parent of this `Entity`. // Therefore, local name and global name // are the same for this `Entity`. this->local_name = global_name; } } void Entity::set_local_name(const std::string& local_name) { if (local_name.empty()) { return; } if (!std::regex_match(local_name, std::regex("[a-zA-Z][a-zA-Z0-9_-]*"))) { return; } yli::ontology::Entity* const parent = this->get_parent(); if (parent == nullptr) { return; } if (parent->has_child(local_name)) { // The name is in use. return; } // Erase old local name. parent->erase_entity(this->local_name); // Set new local name. parent->add_entity(local_name, this); this->local_name = local_name; if (parent == this->universe) { // Special case: this `Entity` is a child of the `Universe`! // Therefore, the local name is also the global name, // and vice versa. This means that the requested // global name must not be in use. this->global_name = local_name; } } } <commit_msg>Add a comment.<commit_after>// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2022 Antti Nuortimo. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #include "entity.hpp" #include "variable.hpp" #include "universe.hpp" #include "family_templates.hpp" #include "entity_factory.hpp" #include "entity_variable_activation.hpp" #include "entity_variable_read.hpp" #include "entity_struct.hpp" #include "variable_struct.hpp" #include "code/ylikuutio/data/any_value.hpp" // Include standard headers #include <cstddef> // std::size_t #include <regex> // std::regex, std::regex_match #include <string> // std::string namespace yli::ontology { class Scene; void Entity::bind_variable(yli::ontology::Variable* const variable) { if (variable != nullptr) { this->parent_of_variables.bind_child(variable); // `variable` with a local name needs to be added to `entity_map` as well. this->add_entity(variable->get_local_name(), variable); } } void Entity::unbind_variable(const std::size_t childID) { this->parent_of_variables.unbind_child(childID); } void Entity::bind_to_universe() { // Requirements: // `this->universe` must not be `nullptr`. yli::ontology::Universe* const universe = this->universe; if (universe == nullptr) { // When `Application` is created, `universe` is still `nullptr`. return; } // Get `entityID` from the `Universe` and set pointer to this `Entity`. universe->bind_entity(this); } void Entity::bind_to_new_parent(yli::ontology::Entity* /* new_parent */) { // Do nothing. // `yli::ontology` classes which support binding must `override` // this `yli::ontology::Entity` base class implementation. } Entity::Entity(yli::ontology::Universe* const universe, const yli::ontology::EntityStruct& entity_struct) : registry(), parent_of_variables(this, &this->registry, ""), // Do not index `parent_of_variables`, index only the variables. parent_of_any_struct_entities(this, &this->registry, "any_struct_entities"), universe { universe }, is_variable { entity_struct.is_variable } { // constructor. // Get `entityID` from `Universe` and set pointer to this `Entity`. this->bind_to_universe(); if (!this->is_variable && this->universe != nullptr && this->universe != this) { this->should_be_rendered = !this->universe->get_is_headless(); yli::ontology::VariableStruct should_be_rendered_variable_struct; should_be_rendered_variable_struct.local_name = "should_be_rendered"; should_be_rendered_variable_struct.activate_callback = &yli::ontology::activate_should_be_rendered; should_be_rendered_variable_struct.read_callback = &yli::ontology::read_should_be_rendered; should_be_rendered_variable_struct.should_call_activate_callback_now = true; this->create_variable(should_be_rendered_variable_struct, yli::data::AnyValue(this->should_be_rendered)); } } Entity::~Entity() { // destructor. if (this->universe == nullptr) { // When leaving the `main` before binding `Application` to `Universe`, // `this->universe` is still `nullptr`. return; } this->universe->unbind_entity(this->entityID); if (!this->global_name.empty() && this->universe != nullptr) { // OK, this `Entity` had a global name, so it's global name shall be erased. this->universe->erase_entity(this->global_name); } // Local names must be erased in the destructors // of classes that inherit `yli::ontology::Entity`! // They can not be erased here in `Entity` destructor, // because `Entity` class does not keep track of the // parent. `Entity` only provides virtual function // `Entity::get_parent`, but that can not be called // from here. } void Entity::activate() { } std::size_t Entity::get_childID() const { return this->childID; } std::string Entity::get_type() const { return this->type_string; } bool Entity::get_can_be_erased() const { return this->can_be_erased; } yli::ontology::Universe* Entity::get_universe() const { return this->universe; } yli::ontology::EntityFactory* Entity::get_entity_factory() const { if (this->universe == nullptr) { return nullptr; } return this->universe->get_entity_factory(); } bool Entity::has_child(const std::string& name) const { return this->registry.is_entity(name); } yli::ontology::Entity* Entity::get_entity(const std::string& name) const { // Requirements: // `name` must not be empty. // `name` must not begin with a dot. // `name` must not end with a dot. std::size_t first_dot_pos = name.find_first_of('.'); if (first_dot_pos == std::string::npos) { // There are no dots in the name. if (!this->registry.is_entity(name)) { return nullptr; } return this->registry.get_entity(name); } // OK, assumedly we have a multi-part name. const std::string first = std::string(name, 0, first_dot_pos); const std::string rest = std::string(name, ++first_dot_pos); if (first.empty()) { // Name must not be empty. return nullptr; } if (!this->registry.is_entity(first)) { return nullptr; } yli::ontology::Entity* entity = this->registry.get_entity(first); if (entity == nullptr) { return nullptr; } return entity->get_entity(rest); } std::string Entity::get_entity_names() const { return this->registry.get_entity_names(); } void Entity::add_entity(const std::string& name, yli::ontology::Entity* const entity) { this->registry.add_entity(entity, name); } void Entity::erase_entity(const std::string& name) { this->registry.erase_entity(name); } void Entity::create_variable(const yli::ontology::VariableStruct& variable_struct, const yli::data::AnyValue& any_value) { if (this->universe == nullptr) { return; } yli::ontology::EntityFactory* const entity_factory = this->universe->get_entity_factory(); if (entity_factory == nullptr) { return; } yli::ontology::VariableStruct new_variable_struct(variable_struct); new_variable_struct.parent = this; entity_factory->create_variable(new_variable_struct, any_value); } bool Entity::has_variable(const std::string& variable_name) const { return this->get(variable_name) != nullptr; } yli::ontology::Variable* Entity::get(const std::string& variable_name) const { return dynamic_cast<yli::ontology::Variable*>(this->registry.get_entity(variable_name)); } bool Entity::set(const std::string& variable_name, const yli::data::AnyValue& variable_new_any_value) { yli::ontology::Variable* const variable = this->get(variable_name); if (variable == nullptr) { return false; } // OK, this is a valid variable name. // Set the variable value and activate it by // calling the corresponding activate callback. variable->set(variable_new_any_value); return true; } std::string Entity::help() const { std::string help_string = "TODO: create general helptext"; return help_string; } std::string Entity::help(const std::string& variable_name) const { yli::ontology::Variable* const variable = this->get(variable_name); if (variable == nullptr) { return this->help(); } return variable->help(); } void Entity::prerender() const { // Requirements: // `this->prerender_callback` must not be `nullptr`. // `this->universe` must not be `nullptr`. if (this->prerender_callback != nullptr && this->universe != nullptr) { this->prerender_callback(this->universe); } } void Entity::postrender() const { // Requirements: // `this->postrender_callback` must not be `nullptr`. // `this->universe` must not be `nullptr`. if (this->postrender_callback != nullptr && this->universe != nullptr) { this->postrender_callback(this->universe); } } std::string Entity::get_global_name() const { return this->global_name; } std::size_t Entity::get_number_of_all_children() const { return this->parent_of_variables.get_number_of_children() + this->get_number_of_non_variable_children(); } std::size_t Entity::get_number_of_all_descendants() const { return yli::ontology::get_number_of_descendants(this->parent_of_variables.child_pointer_vector) + yli::ontology::get_number_of_descendants(this->parent_of_any_struct_entities.child_pointer_vector) + this->get_number_of_descendants(); } std::size_t Entity::get_number_of_variables() const { return this->parent_of_variables.get_number_of_children(); } std::size_t Entity::get_number_of_non_variable_children() const { return this->parent_of_any_struct_entities.get_number_of_children() + this->get_number_of_children(); } std::string Entity::get_local_name() const { return this->local_name; } void Entity::set_global_name(const std::string& global_name) { // Requirements: // `this->universe` must not be `nullptr`. // `global_name` must not be already in use. if (global_name.empty()) { return; } if (!std::regex_match(global_name, std::regex("[a-zA-Z][a-zA-Z0-9_-]*"))) { return; } if (this->universe == nullptr) { return; } if (this->universe->has_child(global_name)) { // The global name is already in use. return; } // Erase old global name. this->universe->erase_entity(this->global_name); // Set new global name. this->global_name = global_name; this->universe->add_entity(global_name, this); if (this->universe == this->get_parent()) { // `Universe` is the parent of this `Entity`. // Therefore, local name and global name // are the same for this `Entity`. this->local_name = global_name; } } void Entity::set_local_name(const std::string& local_name) { if (local_name.empty()) { return; } if (!std::regex_match(local_name, std::regex("[a-zA-Z][a-zA-Z0-9_-]*"))) { return; } yli::ontology::Entity* const parent = this->get_parent(); if (parent == nullptr) { return; } if (parent->has_child(local_name)) { // The name is in use. return; } // Erase old local name. parent->erase_entity(this->local_name); // Set new local name. parent->add_entity(local_name, this); this->local_name = local_name; if (parent == this->universe) { // Special case: this `Entity` is a child of the `Universe`! // Therefore, the local name is also the global name, // and vice versa. This means that the requested // global name must not be in use. this->global_name = local_name; } } } <|endoftext|>
<commit_before>/* * File: Node.hpp * Author: iMer * * Created on 3. Juli 2014, 01:00 */ #ifndef ENGINE_NODE_HPP #define ENGINE_NODE_HPP #include <list> #include <mutex> #include "SFML/Graphics/Drawable.hpp" #include "SFML/Graphics/Transformable.hpp" #include "SFML/Graphics/RenderTarget.hpp" #include "SFML/Graphics/RenderStates.hpp" #include "SFML/System/Time.hpp" #include "Box2D/Box2D.h" #include "util/Event.hpp" #include "util/math.hpp" #include <json/json.h> namespace engine { class Scene; class Factory; struct physicsTransform { public: b2Vec2 pos; b2Vec2 vel; float rot; float rotVel; physicsTransform() : pos(0, 0), vel(0, 0), rot(0), rotVel(0) { } }; enum NodeType{ NT_NONE, NT_SPRITE, NT_SCENE, NT_BUTTON, NT_PARTICLESYSTEM, NT_TEXT, NT_END }; enum OriginType { OT_NONE, OT_TOPLEFT, OT_TOPRIGHT, OT_TOPCENTER, OT_CENTERLEFT, OT_CENTERRIGHT, OT_CENTERCENTER, OT_BOTTOMLEFT, OT_BOTTOMRIGHT, OT_BOTTOMCENTER }; class Node : public sf::Transformable, public sf::NonCopyable { protected: // mutex for locking things accessed in the graphics and logic thread, mainly when copying over position info and such std::recursive_mutex m_mutex; // prevent deletion while in use std::recursive_mutex m_deleteMutex; std::list<Node*> m_children; Scene* m_scene; Node* m_parent; b2Body* m_body; b2Joint* m_parentJoint; physicsTransform m_physicsTransform; sf::Vector2f m_size; bool m_opaque; // Update and render it bool m_active; bool m_destroy; bool m_render; std::string m_identifier; std::string m_filename; bool m_flipped; // Update origin based on size OriginType m_originType; float m_despawnTime; public: Node(Scene* scene); virtual ~Node(); void AddNode(Node* node); void RemoveNode(Node* node); void SetScene(Scene* scene); Scene* GetScene() const; Node* GetParent() const; sf::Transform GetGlobalTransform(); sf::Vector2f GetGlobalPosition(); virtual void update(sf::Time interval); virtual void draw(sf::RenderTarget& target, sf::RenderStates states, float delta); virtual bool initialize(Json::Value& root); // callback once initializing is done and all children are added virtual void OnInitializeDone() {}; virtual uint8_t GetType() const; void SetOpaque(bool lightBlocker); bool IsOpaque() const; void SetPosition(float x, float y); sf::Vector2f GetPosition() const; b2Body* GetBody() const; b2Joint* GetParentJoint() const; void SetActive(bool active); bool IsActive() const; std::list<Node*>& GetChildren(); virtual void SetSize(sf::Vector2f size); const sf::Vector2f& GetSize() const; void Delete(); void SetIdentifier(std::string indentifier); std::string GetIdentifier() const; void SetRender(bool render) { m_render = render; } bool IsRender() const { return m_render; } util::Event<const Node*> OnDelete; Node* GetChildByID(std::string); void SetFilename(std::string filename) { m_filename = filename; } std::string GetFilename() const { return m_filename; } void SetRotation(float deg); float GetRotation(); virtual void SetFlipped(bool flipped) { m_flipped = flipped; } bool IsFlipped() const { return m_flipped; } protected: friend Factory; void SetParent(Node* parent); virtual void OnUpdate(sf::Time interval) { } virtual void OnDraw(sf::RenderTarget& target, sf::RenderStates states, float delta) { } virtual void PostDraw(sf::RenderTarget& target, sf::RenderStates states, float delta) { } void UpdatePhysicsTransform(); void UpdateTransform(float delta); virtual void OnRemoveNode(Node* node){ } }; } #endif /* ENGINE_NODE_HPP */ <commit_msg>Make setactive virtual<commit_after>/* * File: Node.hpp * Author: iMer * * Created on 3. Juli 2014, 01:00 */ #ifndef ENGINE_NODE_HPP #define ENGINE_NODE_HPP #include <list> #include <mutex> #include "SFML/Graphics/Drawable.hpp" #include "SFML/Graphics/Transformable.hpp" #include "SFML/Graphics/RenderTarget.hpp" #include "SFML/Graphics/RenderStates.hpp" #include "SFML/System/Time.hpp" #include "Box2D/Box2D.h" #include "util/Event.hpp" #include "util/math.hpp" #include <json/json.h> namespace engine { class Scene; class Factory; struct physicsTransform { public: b2Vec2 pos; b2Vec2 vel; float rot; float rotVel; physicsTransform() : pos(0, 0), vel(0, 0), rot(0), rotVel(0) { } }; enum NodeType{ NT_NONE, NT_SPRITE, NT_SCENE, NT_BUTTON, NT_PARTICLESYSTEM, NT_TEXT, NT_END }; enum OriginType { OT_NONE, OT_TOPLEFT, OT_TOPRIGHT, OT_TOPCENTER, OT_CENTERLEFT, OT_CENTERRIGHT, OT_CENTERCENTER, OT_BOTTOMLEFT, OT_BOTTOMRIGHT, OT_BOTTOMCENTER }; class Node : public sf::Transformable, public sf::NonCopyable { protected: // mutex for locking things accessed in the graphics and logic thread, mainly when copying over position info and such std::recursive_mutex m_mutex; // prevent deletion while in use std::recursive_mutex m_deleteMutex; std::list<Node*> m_children; Scene* m_scene; Node* m_parent; b2Body* m_body; b2Joint* m_parentJoint; physicsTransform m_physicsTransform; sf::Vector2f m_size; bool m_opaque; // Update and render it bool m_active; bool m_destroy; bool m_render; std::string m_identifier; std::string m_filename; bool m_flipped; // Update origin based on size OriginType m_originType; float m_despawnTime; public: Node(Scene* scene); virtual ~Node(); void AddNode(Node* node); void RemoveNode(Node* node); void SetScene(Scene* scene); Scene* GetScene() const; Node* GetParent() const; sf::Transform GetGlobalTransform(); sf::Vector2f GetGlobalPosition(); virtual void update(sf::Time interval); virtual void draw(sf::RenderTarget& target, sf::RenderStates states, float delta); virtual bool initialize(Json::Value& root); // callback once initializing is done and all children are added virtual void OnInitializeDone() {}; virtual uint8_t GetType() const; void SetOpaque(bool lightBlocker); bool IsOpaque() const; void SetPosition(float x, float y); sf::Vector2f GetPosition() const; b2Body* GetBody() const; b2Joint* GetParentJoint() const; virtual void SetActive(bool active); bool IsActive() const; std::list<Node*>& GetChildren(); virtual void SetSize(sf::Vector2f size); const sf::Vector2f& GetSize() const; void Delete(); void SetIdentifier(std::string indentifier); std::string GetIdentifier() const; void SetRender(bool render) { m_render = render; } bool IsRender() const { return m_render; } util::Event<const Node*> OnDelete; Node* GetChildByID(std::string); void SetFilename(std::string filename) { m_filename = filename; } std::string GetFilename() const { return m_filename; } void SetRotation(float deg); float GetRotation(); virtual void SetFlipped(bool flipped) { m_flipped = flipped; } bool IsFlipped() const { return m_flipped; } protected: friend Factory; void SetParent(Node* parent); virtual void OnUpdate(sf::Time interval) { } virtual void OnDraw(sf::RenderTarget& target, sf::RenderStates states, float delta) { } virtual void PostDraw(sf::RenderTarget& target, sf::RenderStates states, float delta) { } void UpdatePhysicsTransform(); void UpdateTransform(float delta); virtual void OnRemoveNode(Node* node){ } }; } #endif /* ENGINE_NODE_HPP */ <|endoftext|>
<commit_before>#pragma once #include "noncopyable.hpp" #include "response.hpp" using namespace cinatra; #define HAS_MEMBER(member)\ template<typename T, typename... Args>struct has_member_##member\ {\ private:\ template<typename U> static auto Check(int) -> decltype(std::declval<U>().member(std::declval<Args>()...), std::true_type()); \ template<typename U> static std::false_type Check(...); \ public:\ enum{ value = std::is_same<decltype(Check<T>(0)), std::true_type>::value }; \ }; \ HAS_MEMBER(Foo) HAS_MEMBER(before) HAS_MEMBER(after) template<typename Func, typename... Args> struct AOP : NonCopyable { AOP(Func&& f) : m_func(std::forward<Func>(f)) { } template<typename T> typename std::enable_if<has_member_before<T, Args...>::value&&has_member_after<T, Args...>::value, bool>::type invoke(Response& res, Args&&... args, T&& aspect) { bool r = false; aspect.before(std::forward<Args>(args)...); if (!res.is_complete()) { r = m_func(std::forward<Args>(args)...); } aspect.after(std::forward<Args>(args)...); return r; } template<typename T> typename std::enable_if<has_member_before<T, Args...>::value&&!has_member_after<T, Args...>::value, bool>::type invoke(Response& res, Args&&... args, T&& aspect) { bool r = false; aspect.before(std::forward<Args>(args)...);//核心逻辑之前的切面逻辑. if (!res.is_complete()) r = m_func(std::forward<Args>(args)...);//核心逻辑. return r; } template<typename T> typename std::enable_if<!has_member_before<T, Args...>::value&&has_member_after<T, Args...>::value, bool>::type invoke(Response& res, Args&&... args, T&& aspect) { bool r = m_func(std::forward<Args>(args)...);//核心逻辑. aspect.after(std::forward<Args>(args)...);//核心逻辑之后的切面逻辑. return r; } template<typename T, typename Self> typename std::enable_if<has_member_before<T, Args...>::value&&has_member_after<T, Args...>::value, bool>::type invoke_member(Response& res, Self* self, Args&&... args, T&& aspect) { bool r = false; aspect.before(std::forward<Args>(args)...);//核心逻辑之前的切面逻辑. if (!res.is_complete()) { r = (*self.*m_func)(std::forward<Args>(args)...);//核心逻辑. } aspect.after(std::forward<Args>(args)...);//核心逻辑之后的切面逻辑. return r; } //template<typename Head, typename... Tail> //void invoke(bool& result, Args&&... args, Head&&headAspect, Tail&&... tailAspect) //{ // headAspect.before(std::forward<Args>(args)...); // invoke(result, std::forward<Args>(args)..., std::forward<Tail>(tailAspect)...); // headAspect.after(std::forward<Args>(args)...); //} private: Func m_func; //被织入的函数. }; template<typename T> using identity_t = T; //AOP的辅助函数,简化调用. template<typename... AP, typename... Args, typename Func> typename std::enable_if<!std::is_member_function_pointer<Func>::value, bool>::type invoke(Response& res, Func&&f, Args&&... args) { AOP<Func, Args...> asp(std::forward<Func>(f)); return asp.invoke(res, std::forward<Args>(args)..., identity_t<AP>()...); } template<typename... AP, typename... Args, typename Func, typename Self> typename std::enable_if<std::is_member_function_pointer<Func>::value, bool>::type invoke(Response& res, Func&&f, Self* self, Args&&... args) { AOP<Func, Args...> asp(std::forward<Func>(f)); return asp.invoke_member(res, self, std::forward<Args>(args)..., identity_t<AP>()...); }<commit_msg>增加选择分支<commit_after>#pragma once #include "noncopyable.hpp" #include "response.hpp" using namespace cinatra; #define HAS_MEMBER(member)\ template<typename T, typename... Args>struct has_member_##member\ {\ private:\ template<typename U> static auto Check(int) -> decltype(std::declval<U>().member(std::declval<Args>()...), std::true_type()); \ template<typename U> static std::false_type Check(...); \ public:\ enum{ value = std::is_same<decltype(Check<T>(0)), std::true_type>::value }; \ }; \ HAS_MEMBER(Foo) HAS_MEMBER(before) HAS_MEMBER(after) template<typename Func, typename... Args> struct AOP : NonCopyable { AOP(Func&& f) : m_func(std::forward<Func>(f)) { } template<typename T> typename std::enable_if<has_member_before<T, Args...>::value&&has_member_after<T, Args...>::value, bool>::type invoke(Response& res, Args&&... args, T&& aspect) { bool r = false; aspect.before(std::forward<Args>(args)...); if (!res.is_complete()) { r = m_func(std::forward<Args>(args)...); } aspect.after(std::forward<Args>(args)...); return r; } template<typename T> typename std::enable_if<has_member_before<T, Args...>::value&&!has_member_after<T, Args...>::value, bool>::type invoke(Response& res, Args&&... args, T&& aspect) { bool r = false; aspect.before(std::forward<Args>(args)...);//核心逻辑之前的切面逻辑. if (!res.is_complete()) r = m_func(std::forward<Args>(args)...);//核心逻辑. return r; } template<typename T> typename std::enable_if<!has_member_before<T, Args...>::value&&has_member_after<T, Args...>::value, bool>::type invoke(Response& res, Args&&... args, T&& aspect) { bool r = m_func(std::forward<Args>(args)...);//核心逻辑. aspect.after(std::forward<Args>(args)...);//核心逻辑之后的切面逻辑. return r; } template<typename T, typename Self> typename std::enable_if<has_member_before<T, Args...>::value&&has_member_after<T, Args...>::value, bool>::type invoke_member(Response& res, Self* self, Args&&... args, T&& aspect) { bool r = false; aspect.before(std::forward<Args>(args)...);//核心逻辑之前的切面逻辑. if (!res.is_complete()) { r = (*self.*m_func)(std::forward<Args>(args)...);//核心逻辑. } aspect.after(std::forward<Args>(args)...);//核心逻辑之后的切面逻辑. return r; } template<typename T, typename Self> typename std::enable_if<has_member_before<T, Args...>::value&&!has_member_after<T, Args...>::value, bool>::type invoke_member(Response& res, Self* self, Args&&... args, T&& aspect) { bool r = false; aspect.before(std::forward<Args>(args)...);//核心逻辑之前的切面逻辑. if (!res.is_complete()) { r = (*self.*m_func)(std::forward<Args>(args)...);//核心逻辑. } return r; } template<typename T, typename Self> typename std::enable_if<!has_member_before<T, Args...>::value&&has_member_after<T, Args...>::value, bool>::type invoke_member(Response& res, Self* self, Args&&... args, T&& aspect) { bool r = false; if (!res.is_complete()) { r = (*self.*m_func)(std::forward<Args>(args)...);//核心逻辑. } aspect.after(std::forward<Args>(args)...);//核心逻辑之后的切面逻辑. return r; } //template<typename Head, typename... Tail> //void invoke(bool& result, Args&&... args, Head&&headAspect, Tail&&... tailAspect) //{ // headAspect.before(std::forward<Args>(args)...); // invoke(result, std::forward<Args>(args)..., std::forward<Tail>(tailAspect)...); // headAspect.after(std::forward<Args>(args)...); //} private: Func m_func; //被织入的函数. }; template<typename T> using identity_t = T; //AOP的辅助函数,简化调用. template<typename... AP, typename... Args, typename Func> typename std::enable_if<!std::is_member_function_pointer<Func>::value, bool>::type invoke(Response& res, Func&&f, Args&&... args) { AOP<Func, Args...> asp(std::forward<Func>(f)); return asp.invoke(res, std::forward<Args>(args)..., identity_t<AP>()...); } template<typename... AP, typename... Args, typename Func, typename Self> typename std::enable_if<std::is_member_function_pointer<Func>::value, bool>::type invoke(Response& res, Func&&f, Self* self, Args&&... args) { AOP<Func, Args...> asp(std::forward<Func>(f)); return asp.invoke_member(res, self, std::forward<Args>(args)..., identity_t<AP>()...); }<|endoftext|>
<commit_before>#ifndef CLUE_CONFIG__ #define CLUE_CONFIG__ #ifdef __GNUC__ # define CLUE_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #endif #ifdef __clang_major__ # define CLUE_CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) #endif #if defined __GNUC__ # if defined __clang_major__ # if CLUE_CLANG_VERSION < 30400 # error CLUE++ requires clang compiler of version 3.4.0 or above. # endif # else # if CLUE_GCC_VERSION < 40801 # error CLUE++ requires gcc of version 4.8.1 or above. # endif # endif #endif #include <cassert> #define CLUE_ASSERT(cond) assert(cond) #endif <commit_msg>use CLUE_NDEBUG to control CLUE_ASSERT<commit_after>#ifndef CLUE_CONFIG__ #define CLUE_CONFIG__ #ifdef __GNUC__ # define CLUE_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #endif #ifdef __clang_major__ # define CLUE_CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) #endif #if defined __GNUC__ # if defined __clang_major__ # if CLUE_CLANG_VERSION < 30400 # error CLUE++ requires clang compiler of version 3.4.0 or above. # endif # else # if CLUE_GCC_VERSION < 40801 # error CLUE++ requires gcc of version 4.8.1 or above. # endif # endif #endif #include <cassert> // to turn CLUE_ASSERT into no-op, one can pre-define CLUE_NDEBUG // #ifndef CLUE_NDEBUG #define CLUE_ASSERT(cond) assert(cond) #else #define CLUE_ASSERT(cond) #endif #endif <|endoftext|>
<commit_before>/** * @file compmanager.cpp * @brief COSSB component manager * @author Byunghun Hwang<[email protected]> * @date 2015. 6. 21 * @details */ #include "manager.hpp" #include "container.hpp" #include "broker.hpp" #include "driver.hpp" #include <list> using namespace std; namespace cossb { namespace manager { component_manager::component_manager() { } component_manager::~component_manager() { stop(); cossb_component_container->destroy(); } bool component_manager::install(const char* component_name) { if(cossb_component_container->add(component_name, new driver::component_driver(component_name))) { cossb_component_container->get_driver(component_name)->setup(); return true; } return false; } bool component_manager::uninstall(const char* component_name) { if(cossb_component_container->exist(component_name)) { cossb_component_container->get_driver(component_name)->stop(); cossb_component_container->remove(component_name); return true; } return false; } bool component_manager::run(const char* component_name) { if(cossb_component_container->exist(component_name)) { cossb_component_container->get_driver(component_name)->run(); return true; } return false; } bool component_manager::run() { for(auto comp:cossb_component_container->_container) { this->run(comp.first.c_str()); } return true; } bool component_manager::stop(const char* component_name) { if(cossb_component_container->exist(component_name)) { cossb_component_container->get_driver(component_name)->stop(); return true; } return false; } bool component_manager::stop() { for(auto comp:cossb_component_container->_container) { this->stop(comp.first.c_str()); } return true; } int component_manager::count() { return 0; } driver::component_driver* component_manager::get_driver(const char* component_name) { if(cossb_component_container->exist(component_name)) { return cossb_component_container->get_driver(component_name); } return nullptr; } } /* namespace manager */ } /* namespace cossb */ <commit_msg>count function was implemented<commit_after>/** * @file compmanager.cpp * @brief COSSB component manager * @author Byunghun Hwang<[email protected]> * @date 2015. 6. 21 * @details */ #include "manager.hpp" #include "container.hpp" #include "broker.hpp" #include "driver.hpp" #include <list> using namespace std; namespace cossb { namespace manager { component_manager::component_manager() { } component_manager::~component_manager() { stop(); cossb_component_container->destroy(); } bool component_manager::install(const char* component_name) { if(cossb_component_container->add(component_name, new driver::component_driver(component_name))) { cossb_component_container->get_driver(component_name)->setup(); return true; } return false; } bool component_manager::uninstall(const char* component_name) { if(cossb_component_container->exist(component_name)) { cossb_component_container->get_driver(component_name)->stop(); cossb_component_container->remove(component_name); return true; } return false; } bool component_manager::run(const char* component_name) { if(cossb_component_container->exist(component_name)) { cossb_component_container->get_driver(component_name)->run(); return true; } return false; } bool component_manager::run() { for(auto comp:cossb_component_container->_container) { this->run(comp.first.c_str()); } return true; } bool component_manager::stop(const char* component_name) { if(cossb_component_container->exist(component_name)) { cossb_component_container->get_driver(component_name)->stop(); return true; } return false; } bool component_manager::stop() { for(auto comp:cossb_component_container->_container) { this->stop(comp.first.c_str()); } return true; } int component_manager::count() { return cossb_component_container->_container.size(); } driver::component_driver* component_manager::get_driver(const char* component_name) { if(cossb_component_container->exist(component_name)) { return cossb_component_container->get_driver(component_name); } return nullptr; } } /* namespace manager */ } /* namespace cossb */ <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/notifications/desktop_notification_service.h" #include "base/memory/ref_counted.h" #include "base/message_loop.h" #include "base/synchronization/waitable_event.h" #include "chrome/browser/notifications/notifications_prefs_cache.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/prefs/scoped_user_pref_update.h" #include "chrome/common/pref_names.h" #include "chrome/test/testing_profile.h" #include "content/browser/browser_thread.h" #include "content/browser/renderer_host/test_render_view_host.h" #include "grit/generated_resources.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebNotificationPresenter.h" namespace { // NotificationsPrefsCache wants to be called on the IO thread. This class // routes calls to the cache on the IO thread. class ThreadProxy : public base::RefCountedThreadSafe<ThreadProxy> { public: ThreadProxy() : io_event_(false, false), ui_event_(false, false), permission_(0) { // The current message loop was already initalized by the test superclass. ui_thread_.reset( new BrowserThread(BrowserThread::UI, MessageLoop::current())); // Create IO thread, start its message loop. io_thread_.reset(new BrowserThread(BrowserThread::IO)); io_thread_->Start(); // Calling PauseIOThread() here isn't safe, because the runnable method // could complete before the constructor is done, deleting |this|. } int CacheHasPermission(NotificationsPrefsCache* cache, const GURL& url) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &ThreadProxy::CacheHasPermissionIO, make_scoped_refptr(cache), url)); io_event_.Signal(); ui_event_.Wait(); // Wait for IO thread to be done. BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &ThreadProxy::PauseIOThreadIO)); return permission_; } void PauseIOThread() { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &ThreadProxy::PauseIOThreadIO)); } void DrainIOThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); io_event_.Signal(); io_thread_->Stop(); } private: friend class base::RefCountedThreadSafe<ThreadProxy>; ~ThreadProxy() { DrainIOThread(); } void PauseIOThreadIO() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); io_event_.Wait(); } void CacheHasPermissionIO(NotificationsPrefsCache* cache, const GURL& url) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); permission_ = cache->HasPermission(url); ui_event_.Signal(); } base::WaitableEvent io_event_; base::WaitableEvent ui_event_; scoped_ptr<BrowserThread> ui_thread_; scoped_ptr<BrowserThread> io_thread_; int permission_; }; class DesktopNotificationServiceTest : public RenderViewHostTestHarness { public: DesktopNotificationServiceTest() { } virtual void SetUp() { RenderViewHostTestHarness::SetUp(); proxy_ = new ThreadProxy; proxy_->PauseIOThread(); // Creates the service, calls InitPrefs() on it which loads data from the // profile into the cache and then puts the cache in io thread mode. service_ = profile()->GetDesktopNotificationService(); cache_ = service_->prefs_cache(); } virtual void TearDown() { // The io thread's waiting on the io_event_ might hold a ref to |proxy_|, // preventing its destruction. Clear that ref. proxy_->DrainIOThread(); RenderViewHostTestHarness::TearDown(); } DesktopNotificationService* service_; NotificationsPrefsCache* cache_; scoped_refptr<ThreadProxy> proxy_; }; TEST_F(DesktopNotificationServiceTest, DefaultContentSettingSentToCache) { // The default pref registered in DesktopNotificationService is "ask", // and that's what sent to the cache. EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting()); // Change the default content setting. This will post a task on the IO thread // to update the cache. service_->SetDefaultContentSetting(CONTENT_SETTING_BLOCK); // The updated pref shouldn't be sent to the cache immediately. EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting()); // Run IO thread tasks. proxy_->DrainIOThread(); // Now that IO thread events have been processed, it should be there. EXPECT_EQ(CONTENT_SETTING_BLOCK, cache_->CachedDefaultContentSetting()); } TEST_F(DesktopNotificationServiceTest, SettingsForSchemes) { GURL url("file:///html/test.html"); EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting()); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, url)); service_->GrantPermission(url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed, proxy_->CacheHasPermission(cache_, url)); service_->DenyPermission(url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied, proxy_->CacheHasPermission(cache_, url)); GURL https_url("https://testurl"); GURL http_url("http://testurl"); EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting()); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, http_url)); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, https_url)); service_->GrantPermission(https_url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed, proxy_->CacheHasPermission(cache_, https_url)); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, http_url)); service_->DenyPermission(http_url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied, proxy_->CacheHasPermission(cache_, http_url)); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed, proxy_->CacheHasPermission(cache_, https_url)); } TEST_F(DesktopNotificationServiceTest, GrantPermissionSentToCache) { GURL url("http://allowed.com"); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, url)); service_->GrantPermission(url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed, proxy_->CacheHasPermission(cache_, url)); } TEST_F(DesktopNotificationServiceTest, DenyPermissionSentToCache) { GURL url("http://denied.com"); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, url)); service_->DenyPermission(url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied, proxy_->CacheHasPermission(cache_, url)); } TEST_F(DesktopNotificationServiceTest, PrefChangesSentToCache) { PrefService* prefs = profile()->GetPrefs(); ListValue* allowed_sites = prefs->GetMutableList(prefs::kDesktopNotificationAllowedOrigins); { allowed_sites->Append(new StringValue(GURL("http://allowed.com").spec())); ScopedUserPrefUpdate updateAllowed( prefs, prefs::kDesktopNotificationAllowedOrigins); } ListValue* denied_sites = prefs->GetMutableList(prefs::kDesktopNotificationDeniedOrigins); { denied_sites->Append(new StringValue(GURL("http://denied.com").spec())); ScopedUserPrefUpdate updateDenied( prefs, prefs::kDesktopNotificationDeniedOrigins); } EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed, proxy_->CacheHasPermission(cache_, GURL("http://allowed.com"))); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied, proxy_->CacheHasPermission(cache_, GURL("http://denied.com"))); } TEST_F(DesktopNotificationServiceTest, GetAllowedOrigins) { service_->GrantPermission(GURL("http://allowed2.com")); service_->GrantPermission(GURL("http://allowed.com")); std::vector<GURL> allowed_origins(service_->GetAllowedOrigins()); ASSERT_EQ(2u, allowed_origins.size()); EXPECT_EQ(GURL("http://allowed2.com"), allowed_origins[0]); EXPECT_EQ(GURL("http://allowed.com"), allowed_origins[1]); } TEST_F(DesktopNotificationServiceTest, GetBlockedOrigins) { service_->DenyPermission(GURL("http://denied2.com")); service_->DenyPermission(GURL("http://denied.com")); std::vector<GURL> denied_origins(service_->GetBlockedOrigins()); ASSERT_EQ(2u, denied_origins.size()); EXPECT_EQ(GURL("http://denied2.com"), denied_origins[0]); EXPECT_EQ(GURL("http://denied.com"), denied_origins[1]); } TEST_F(DesktopNotificationServiceTest, ResetAllSentToCache) { GURL allowed_url("http://allowed.com"); service_->GrantPermission(allowed_url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed, proxy_->CacheHasPermission(cache_, allowed_url)); GURL denied_url("http://denied.com"); service_->DenyPermission(denied_url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied, proxy_->CacheHasPermission(cache_, denied_url)); service_->ResetAllOrigins(); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, allowed_url)); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, denied_url)); } TEST_F(DesktopNotificationServiceTest, ResetAllowedSentToCache) { GURL allowed_url("http://allowed.com"); service_->GrantPermission(allowed_url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed, proxy_->CacheHasPermission(cache_, allowed_url)); service_->ResetAllowedOrigin(allowed_url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, allowed_url)); } TEST_F(DesktopNotificationServiceTest, ResetBlockedSentToCache) { GURL denied_url("http://denied.com"); service_->DenyPermission(denied_url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied, proxy_->CacheHasPermission(cache_, denied_url)); service_->ResetBlockedOrigin(denied_url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, denied_url)); } } // namespace <commit_msg>Get rid of PrefService::GetMutableDictionary/GetMutableList<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/notifications/desktop_notification_service.h" #include "base/memory/ref_counted.h" #include "base/message_loop.h" #include "base/synchronization/waitable_event.h" #include "chrome/browser/notifications/notifications_prefs_cache.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/prefs/scoped_user_pref_update.h" #include "chrome/common/pref_names.h" #include "chrome/test/testing_profile.h" #include "content/browser/browser_thread.h" #include "content/browser/renderer_host/test_render_view_host.h" #include "grit/generated_resources.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebNotificationPresenter.h" namespace { // NotificationsPrefsCache wants to be called on the IO thread. This class // routes calls to the cache on the IO thread. class ThreadProxy : public base::RefCountedThreadSafe<ThreadProxy> { public: ThreadProxy() : io_event_(false, false), ui_event_(false, false), permission_(0) { // The current message loop was already initalized by the test superclass. ui_thread_.reset( new BrowserThread(BrowserThread::UI, MessageLoop::current())); // Create IO thread, start its message loop. io_thread_.reset(new BrowserThread(BrowserThread::IO)); io_thread_->Start(); // Calling PauseIOThread() here isn't safe, because the runnable method // could complete before the constructor is done, deleting |this|. } int CacheHasPermission(NotificationsPrefsCache* cache, const GURL& url) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &ThreadProxy::CacheHasPermissionIO, make_scoped_refptr(cache), url)); io_event_.Signal(); ui_event_.Wait(); // Wait for IO thread to be done. BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &ThreadProxy::PauseIOThreadIO)); return permission_; } void PauseIOThread() { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &ThreadProxy::PauseIOThreadIO)); } void DrainIOThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); io_event_.Signal(); io_thread_->Stop(); } private: friend class base::RefCountedThreadSafe<ThreadProxy>; ~ThreadProxy() { DrainIOThread(); } void PauseIOThreadIO() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); io_event_.Wait(); } void CacheHasPermissionIO(NotificationsPrefsCache* cache, const GURL& url) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); permission_ = cache->HasPermission(url); ui_event_.Signal(); } base::WaitableEvent io_event_; base::WaitableEvent ui_event_; scoped_ptr<BrowserThread> ui_thread_; scoped_ptr<BrowserThread> io_thread_; int permission_; }; class DesktopNotificationServiceTest : public RenderViewHostTestHarness { public: DesktopNotificationServiceTest() { } virtual void SetUp() { RenderViewHostTestHarness::SetUp(); proxy_ = new ThreadProxy; proxy_->PauseIOThread(); // Creates the service, calls InitPrefs() on it which loads data from the // profile into the cache and then puts the cache in io thread mode. service_ = profile()->GetDesktopNotificationService(); cache_ = service_->prefs_cache(); } virtual void TearDown() { // The io thread's waiting on the io_event_ might hold a ref to |proxy_|, // preventing its destruction. Clear that ref. proxy_->DrainIOThread(); RenderViewHostTestHarness::TearDown(); } DesktopNotificationService* service_; NotificationsPrefsCache* cache_; scoped_refptr<ThreadProxy> proxy_; }; TEST_F(DesktopNotificationServiceTest, DefaultContentSettingSentToCache) { // The default pref registered in DesktopNotificationService is "ask", // and that's what sent to the cache. EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting()); // Change the default content setting. This will post a task on the IO thread // to update the cache. service_->SetDefaultContentSetting(CONTENT_SETTING_BLOCK); // The updated pref shouldn't be sent to the cache immediately. EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting()); // Run IO thread tasks. proxy_->DrainIOThread(); // Now that IO thread events have been processed, it should be there. EXPECT_EQ(CONTENT_SETTING_BLOCK, cache_->CachedDefaultContentSetting()); } TEST_F(DesktopNotificationServiceTest, SettingsForSchemes) { GURL url("file:///html/test.html"); EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting()); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, url)); service_->GrantPermission(url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed, proxy_->CacheHasPermission(cache_, url)); service_->DenyPermission(url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied, proxy_->CacheHasPermission(cache_, url)); GURL https_url("https://testurl"); GURL http_url("http://testurl"); EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting()); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, http_url)); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, https_url)); service_->GrantPermission(https_url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed, proxy_->CacheHasPermission(cache_, https_url)); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, http_url)); service_->DenyPermission(http_url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied, proxy_->CacheHasPermission(cache_, http_url)); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed, proxy_->CacheHasPermission(cache_, https_url)); } TEST_F(DesktopNotificationServiceTest, GrantPermissionSentToCache) { GURL url("http://allowed.com"); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, url)); service_->GrantPermission(url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed, proxy_->CacheHasPermission(cache_, url)); } TEST_F(DesktopNotificationServiceTest, DenyPermissionSentToCache) { GURL url("http://denied.com"); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, url)); service_->DenyPermission(url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied, proxy_->CacheHasPermission(cache_, url)); } TEST_F(DesktopNotificationServiceTest, PrefChangesSentToCache) { PrefService* prefs = profile()->GetPrefs(); { ListPrefUpdate update_allowed_origins( prefs, prefs::kDesktopNotificationAllowedOrigins); ListValue* allowed_origins = update_allowed_origins.Get(); allowed_origins->Append(new StringValue(GURL("http://allowed.com").spec())); } { ListPrefUpdate update_denied_origins( prefs, prefs::kDesktopNotificationDeniedOrigins); ListValue* denied_origins = update_denied_origins.Get(); denied_origins->Append(new StringValue(GURL("http://denied.com").spec())); } EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed, proxy_->CacheHasPermission(cache_, GURL("http://allowed.com"))); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied, proxy_->CacheHasPermission(cache_, GURL("http://denied.com"))); } TEST_F(DesktopNotificationServiceTest, GetAllowedOrigins) { service_->GrantPermission(GURL("http://allowed2.com")); service_->GrantPermission(GURL("http://allowed.com")); std::vector<GURL> allowed_origins(service_->GetAllowedOrigins()); ASSERT_EQ(2u, allowed_origins.size()); EXPECT_EQ(GURL("http://allowed2.com"), allowed_origins[0]); EXPECT_EQ(GURL("http://allowed.com"), allowed_origins[1]); } TEST_F(DesktopNotificationServiceTest, GetBlockedOrigins) { service_->DenyPermission(GURL("http://denied2.com")); service_->DenyPermission(GURL("http://denied.com")); std::vector<GURL> denied_origins(service_->GetBlockedOrigins()); ASSERT_EQ(2u, denied_origins.size()); EXPECT_EQ(GURL("http://denied2.com"), denied_origins[0]); EXPECT_EQ(GURL("http://denied.com"), denied_origins[1]); } TEST_F(DesktopNotificationServiceTest, ResetAllSentToCache) { GURL allowed_url("http://allowed.com"); service_->GrantPermission(allowed_url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed, proxy_->CacheHasPermission(cache_, allowed_url)); GURL denied_url("http://denied.com"); service_->DenyPermission(denied_url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied, proxy_->CacheHasPermission(cache_, denied_url)); service_->ResetAllOrigins(); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, allowed_url)); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, denied_url)); } TEST_F(DesktopNotificationServiceTest, ResetAllowedSentToCache) { GURL allowed_url("http://allowed.com"); service_->GrantPermission(allowed_url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed, proxy_->CacheHasPermission(cache_, allowed_url)); service_->ResetAllowedOrigin(allowed_url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, allowed_url)); } TEST_F(DesktopNotificationServiceTest, ResetBlockedSentToCache) { GURL denied_url("http://denied.com"); service_->DenyPermission(denied_url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied, proxy_->CacheHasPermission(cache_, denied_url)); service_->ResetBlockedOrigin(denied_url); EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed, proxy_->CacheHasPermission(cache_, denied_url)); } } // namespace <|endoftext|>
<commit_before>/* * libjingle * Copyright 2012, Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "talk/app/webrtc/dtmfsender.h" #include <set> #include <string> #include <vector> #include "talk/app/webrtc/audiotrack.h" #include "talk/base/gunit.h" #include "talk/base/logging.h" #include "talk/base/timeutils.h" using webrtc::AudioTrackInterface; using webrtc::AudioTrack; using webrtc::DtmfProviderInterface; using webrtc::DtmfSender; using webrtc::DtmfSenderObserverInterface; static const char kTestAudioLabel[] = "test_audio_track"; static const int kMaxWaitMs = 3000; class FakeDtmfObserver : public DtmfSenderObserverInterface { public: FakeDtmfObserver() : completed_(false) {} // Implements DtmfSenderObserverInterface. virtual void OnToneChange(const std::string& tone) OVERRIDE { LOG(LS_VERBOSE) << "FakeDtmfObserver::OnToneChange '" << tone << "'."; tones_.push_back(tone); if (tone.empty()) { completed_ = true; } } // getters const std::vector<std::string>& tones() const { return tones_; } bool completed() const { return completed_; } private: std::vector<std::string> tones_; bool completed_; }; class FakeDtmfProvider : public DtmfProviderInterface { public: struct DtmfInfo { DtmfInfo(int code, int duration, int gap) : code(code), duration(duration), gap(gap) {} int code; int duration; int gap; }; FakeDtmfProvider() : last_insert_dtmf_call_(0) {} ~FakeDtmfProvider() { SignalDestroyed(); } // Implements DtmfProviderInterface. virtual bool CanInsertDtmf(const std::string& track_label) OVERRIDE { return (can_insert_dtmf_tracks_.count(track_label) != 0); } virtual bool InsertDtmf(const std::string& track_label, int code, int duration) OVERRIDE { int gap = 0; // TODO(ronghuawu): Make the timer (basically the talk_base::TimeNanos) // mockable and use a fake timer in the unit tests. if (last_insert_dtmf_call_ > 0) { gap = static_cast<int>(talk_base::Time() - last_insert_dtmf_call_); } last_insert_dtmf_call_ = talk_base::Time(); LOG(LS_VERBOSE) << "FakeDtmfProvider::InsertDtmf code=" << code << " duration=" << duration << " gap=" << gap << "."; dtmf_info_queue_.push_back(DtmfInfo(code, duration, gap)); return true; } virtual sigslot::signal0<>* GetOnDestroyedSignal() { return &SignalDestroyed; } // getter and setter const std::vector<DtmfInfo>& dtmf_info_queue() const { return dtmf_info_queue_; } // helper functions void AddCanInsertDtmfTrack(const std::string& label) { can_insert_dtmf_tracks_.insert(label); } void RemoveCanInsertDtmfTrack(const std::string& label) { can_insert_dtmf_tracks_.erase(label); } private: std::set<std::string> can_insert_dtmf_tracks_; std::vector<DtmfInfo> dtmf_info_queue_; int64 last_insert_dtmf_call_; sigslot::signal0<> SignalDestroyed; }; class DtmfSenderTest : public testing::Test { protected: DtmfSenderTest() : track_(AudioTrack::Create(kTestAudioLabel, NULL)), observer_(new talk_base::RefCountedObject<FakeDtmfObserver>()), provider_(new FakeDtmfProvider()) { provider_->AddCanInsertDtmfTrack(kTestAudioLabel); dtmf_ = DtmfSender::Create(track_, talk_base::Thread::Current(), provider_.get()); dtmf_->RegisterObserver(observer_.get()); } ~DtmfSenderTest() { if (dtmf_.get()) { dtmf_->UnregisterObserver(); } } // Constructs a list of DtmfInfo from |tones|, |duration| and // |inter_tone_gap|. void GetDtmfInfoFromString(const std::string& tones, int duration, int inter_tone_gap, std::vector<FakeDtmfProvider::DtmfInfo>* dtmfs) { // Init extra_delay as -inter_tone_gap - duration to ensure the first // DtmfInfo's gap field will be 0. int extra_delay = -1 * (inter_tone_gap + duration); std::string::const_iterator it = tones.begin(); for (; it != tones.end(); ++it) { char tone = *it; int code = 0; webrtc::GetDtmfCode(tone, &code); if (tone == ',') { extra_delay = 2000; // 2 seconds } else { dtmfs->push_back(FakeDtmfProvider::DtmfInfo(code, duration, duration + inter_tone_gap + extra_delay)); extra_delay = 0; } } } void VerifyExpectedState(AudioTrackInterface* track, const std::string& tones, int duration, int inter_tone_gap) { EXPECT_EQ(track, dtmf_->track()); EXPECT_EQ(tones, dtmf_->tones()); EXPECT_EQ(duration, dtmf_->duration()); EXPECT_EQ(inter_tone_gap, dtmf_->inter_tone_gap()); } // Verify the provider got all the expected calls. void VerifyOnProvider(const std::string& tones, int duration, int inter_tone_gap) { std::vector<FakeDtmfProvider::DtmfInfo> dtmf_queue_ref; GetDtmfInfoFromString(tones, duration, inter_tone_gap, &dtmf_queue_ref); VerifyOnProvider(dtmf_queue_ref); } void VerifyOnProvider( const std::vector<FakeDtmfProvider::DtmfInfo>& dtmf_queue_ref) { const std::vector<FakeDtmfProvider::DtmfInfo>& dtmf_queue = provider_->dtmf_info_queue(); ASSERT_EQ(dtmf_queue_ref.size(), dtmf_queue.size()); std::vector<FakeDtmfProvider::DtmfInfo>::const_iterator it_ref = dtmf_queue_ref.begin(); std::vector<FakeDtmfProvider::DtmfInfo>::const_iterator it = dtmf_queue.begin(); while (it_ref != dtmf_queue_ref.end() && it != dtmf_queue.end()) { EXPECT_EQ(it_ref->code, it->code); EXPECT_EQ(it_ref->duration, it->duration); // Allow ~20ms error. EXPECT_GE(it_ref->gap, it->gap - 20); EXPECT_LE(it_ref->gap, it->gap + 20); ++it_ref; ++it; } } // Verify the observer got all the expected callbacks. void VerifyOnObserver(const std::string& tones_ref) { const std::vector<std::string>& tones = observer_->tones(); // The observer will get an empty string at the end. EXPECT_EQ(tones_ref.size() + 1, tones.size()); EXPECT_TRUE(tones.back().empty()); std::string::const_iterator it_ref = tones_ref.begin(); std::vector<std::string>::const_iterator it = tones.begin(); while (it_ref != tones_ref.end() && it != tones.end()) { EXPECT_EQ(*it_ref, it->at(0)); ++it_ref; ++it; } } talk_base::scoped_refptr<AudioTrackInterface> track_; talk_base::scoped_ptr<FakeDtmfObserver> observer_; talk_base::scoped_ptr<FakeDtmfProvider> provider_; talk_base::scoped_refptr<DtmfSender> dtmf_; }; TEST_F(DtmfSenderTest, CanInsertDtmf) { EXPECT_TRUE(dtmf_->CanInsertDtmf()); provider_->RemoveCanInsertDtmfTrack(kTestAudioLabel); EXPECT_FALSE(dtmf_->CanInsertDtmf()); } TEST_F(DtmfSenderTest, InsertDtmf) { std::string tones = "@1%a&*$"; int duration = 100; int inter_tone_gap = 50; EXPECT_TRUE(dtmf_->InsertDtmf(tones, duration, inter_tone_gap)); EXPECT_TRUE_WAIT(observer_->completed(), kMaxWaitMs); // The unrecognized characters should be ignored. std::string known_tones = "1a*"; VerifyOnProvider(known_tones, duration, inter_tone_gap); VerifyOnObserver(known_tones); } TEST_F(DtmfSenderTest, InsertDtmfTwice) { std::string tones1 = "12"; std::string tones2 = "ab"; int duration = 100; int inter_tone_gap = 50; EXPECT_TRUE(dtmf_->InsertDtmf(tones1, duration, inter_tone_gap)); VerifyExpectedState(track_, tones1, duration, inter_tone_gap); // Wait until the first tone got sent. EXPECT_TRUE_WAIT(observer_->tones().size() == 1, kMaxWaitMs); VerifyExpectedState(track_, "2", duration, inter_tone_gap); // Insert with another tone buffer. EXPECT_TRUE(dtmf_->InsertDtmf(tones2, duration, inter_tone_gap)); VerifyExpectedState(track_, tones2, duration, inter_tone_gap); // Wait until it's completed. EXPECT_TRUE_WAIT(observer_->completed(), kMaxWaitMs); std::vector<FakeDtmfProvider::DtmfInfo> dtmf_queue_ref; GetDtmfInfoFromString("1", duration, inter_tone_gap, &dtmf_queue_ref); GetDtmfInfoFromString("ab", duration, inter_tone_gap, &dtmf_queue_ref); VerifyOnProvider(dtmf_queue_ref); VerifyOnObserver("1ab"); } TEST_F(DtmfSenderTest, InsertDtmfWhileProviderIsDeleted) { std::string tones = "@1%a&*$"; int duration = 100; int inter_tone_gap = 50; EXPECT_TRUE(dtmf_->InsertDtmf(tones, duration, inter_tone_gap)); // Wait until the first tone got sent. EXPECT_TRUE_WAIT(observer_->tones().size() == 1, kMaxWaitMs); // Delete provider. provider_.reset(); // The queue should be discontinued so no more tone callbacks. WAIT(false, 200); EXPECT_EQ(1U, observer_->tones().size()); } TEST_F(DtmfSenderTest, InsertDtmfWhileSenderIsDeleted) { std::string tones = "@1%a&*$"; int duration = 100; int inter_tone_gap = 50; EXPECT_TRUE(dtmf_->InsertDtmf(tones, duration, inter_tone_gap)); // Wait until the first tone got sent. EXPECT_TRUE_WAIT(observer_->tones().size() == 1, kMaxWaitMs); // Delete the sender. dtmf_ = NULL; // The queue should be discontinued so no more tone callbacks. WAIT(false, 200); EXPECT_EQ(1U, observer_->tones().size()); } TEST_F(DtmfSenderTest, InsertEmptyTonesToCancelPreviousTask) { std::string tones1 = "12"; std::string tones2 = ""; int duration = 100; int inter_tone_gap = 50; EXPECT_TRUE(dtmf_->InsertDtmf(tones1, duration, inter_tone_gap)); // Wait until the first tone got sent. EXPECT_TRUE_WAIT(observer_->tones().size() == 1, kMaxWaitMs); // Insert with another tone buffer. EXPECT_TRUE(dtmf_->InsertDtmf(tones2, duration, inter_tone_gap)); // Wait until it's completed. EXPECT_TRUE_WAIT(observer_->completed(), kMaxWaitMs); std::vector<FakeDtmfProvider::DtmfInfo> dtmf_queue_ref; GetDtmfInfoFromString("1", duration, inter_tone_gap, &dtmf_queue_ref); VerifyOnProvider(dtmf_queue_ref); VerifyOnObserver("1"); } TEST_F(DtmfSenderTest, InsertDtmfWithCommaAsDelay) { std::string tones = "3,4"; int duration = 100; int inter_tone_gap = 50; EXPECT_TRUE(dtmf_->InsertDtmf(tones, duration, inter_tone_gap)); EXPECT_TRUE_WAIT(observer_->completed(), kMaxWaitMs); VerifyOnProvider(tones, duration, inter_tone_gap); VerifyOnObserver(tones); } TEST_F(DtmfSenderTest, TryInsertDtmfWhenItDoesNotWork) { std::string tones = "3,4"; int duration = 100; int inter_tone_gap = 50; provider_->RemoveCanInsertDtmfTrack(kTestAudioLabel); EXPECT_FALSE(dtmf_->InsertDtmf(tones, duration, inter_tone_gap)); } TEST_F(DtmfSenderTest, InsertDtmfWithInvalidDurationOrGap) { std::string tones = "3,4"; int duration = 100; int inter_tone_gap = 50; EXPECT_FALSE(dtmf_->InsertDtmf(tones, 6001, inter_tone_gap)); EXPECT_FALSE(dtmf_->InsertDtmf(tones, 69, inter_tone_gap)); EXPECT_FALSE(dtmf_->InsertDtmf(tones, duration, 49)); EXPECT_TRUE(dtmf_->InsertDtmf(tones, duration, inter_tone_gap)); } <commit_msg>Increase the dtmfsender test toleration to 100ms to avoid flaky. <commit_after>/* * libjingle * Copyright 2012, Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "talk/app/webrtc/dtmfsender.h" #include <set> #include <string> #include <vector> #include "talk/app/webrtc/audiotrack.h" #include "talk/base/gunit.h" #include "talk/base/logging.h" #include "talk/base/timeutils.h" using webrtc::AudioTrackInterface; using webrtc::AudioTrack; using webrtc::DtmfProviderInterface; using webrtc::DtmfSender; using webrtc::DtmfSenderObserverInterface; static const char kTestAudioLabel[] = "test_audio_track"; static const int kMaxWaitMs = 3000; class FakeDtmfObserver : public DtmfSenderObserverInterface { public: FakeDtmfObserver() : completed_(false) {} // Implements DtmfSenderObserverInterface. virtual void OnToneChange(const std::string& tone) OVERRIDE { LOG(LS_VERBOSE) << "FakeDtmfObserver::OnToneChange '" << tone << "'."; tones_.push_back(tone); if (tone.empty()) { completed_ = true; } } // getters const std::vector<std::string>& tones() const { return tones_; } bool completed() const { return completed_; } private: std::vector<std::string> tones_; bool completed_; }; class FakeDtmfProvider : public DtmfProviderInterface { public: struct DtmfInfo { DtmfInfo(int code, int duration, int gap) : code(code), duration(duration), gap(gap) {} int code; int duration; int gap; }; FakeDtmfProvider() : last_insert_dtmf_call_(0) {} ~FakeDtmfProvider() { SignalDestroyed(); } // Implements DtmfProviderInterface. virtual bool CanInsertDtmf(const std::string& track_label) OVERRIDE { return (can_insert_dtmf_tracks_.count(track_label) != 0); } virtual bool InsertDtmf(const std::string& track_label, int code, int duration) OVERRIDE { int gap = 0; // TODO(ronghuawu): Make the timer (basically the talk_base::TimeNanos) // mockable and use a fake timer in the unit tests. if (last_insert_dtmf_call_ > 0) { gap = static_cast<int>(talk_base::Time() - last_insert_dtmf_call_); } last_insert_dtmf_call_ = talk_base::Time(); LOG(LS_VERBOSE) << "FakeDtmfProvider::InsertDtmf code=" << code << " duration=" << duration << " gap=" << gap << "."; dtmf_info_queue_.push_back(DtmfInfo(code, duration, gap)); return true; } virtual sigslot::signal0<>* GetOnDestroyedSignal() { return &SignalDestroyed; } // getter and setter const std::vector<DtmfInfo>& dtmf_info_queue() const { return dtmf_info_queue_; } // helper functions void AddCanInsertDtmfTrack(const std::string& label) { can_insert_dtmf_tracks_.insert(label); } void RemoveCanInsertDtmfTrack(const std::string& label) { can_insert_dtmf_tracks_.erase(label); } private: std::set<std::string> can_insert_dtmf_tracks_; std::vector<DtmfInfo> dtmf_info_queue_; int64 last_insert_dtmf_call_; sigslot::signal0<> SignalDestroyed; }; class DtmfSenderTest : public testing::Test { protected: DtmfSenderTest() : track_(AudioTrack::Create(kTestAudioLabel, NULL)), observer_(new talk_base::RefCountedObject<FakeDtmfObserver>()), provider_(new FakeDtmfProvider()) { provider_->AddCanInsertDtmfTrack(kTestAudioLabel); dtmf_ = DtmfSender::Create(track_, talk_base::Thread::Current(), provider_.get()); dtmf_->RegisterObserver(observer_.get()); } ~DtmfSenderTest() { if (dtmf_.get()) { dtmf_->UnregisterObserver(); } } // Constructs a list of DtmfInfo from |tones|, |duration| and // |inter_tone_gap|. void GetDtmfInfoFromString(const std::string& tones, int duration, int inter_tone_gap, std::vector<FakeDtmfProvider::DtmfInfo>* dtmfs) { // Init extra_delay as -inter_tone_gap - duration to ensure the first // DtmfInfo's gap field will be 0. int extra_delay = -1 * (inter_tone_gap + duration); std::string::const_iterator it = tones.begin(); for (; it != tones.end(); ++it) { char tone = *it; int code = 0; webrtc::GetDtmfCode(tone, &code); if (tone == ',') { extra_delay = 2000; // 2 seconds } else { dtmfs->push_back(FakeDtmfProvider::DtmfInfo(code, duration, duration + inter_tone_gap + extra_delay)); extra_delay = 0; } } } void VerifyExpectedState(AudioTrackInterface* track, const std::string& tones, int duration, int inter_tone_gap) { EXPECT_EQ(track, dtmf_->track()); EXPECT_EQ(tones, dtmf_->tones()); EXPECT_EQ(duration, dtmf_->duration()); EXPECT_EQ(inter_tone_gap, dtmf_->inter_tone_gap()); } // Verify the provider got all the expected calls. void VerifyOnProvider(const std::string& tones, int duration, int inter_tone_gap) { std::vector<FakeDtmfProvider::DtmfInfo> dtmf_queue_ref; GetDtmfInfoFromString(tones, duration, inter_tone_gap, &dtmf_queue_ref); VerifyOnProvider(dtmf_queue_ref); } void VerifyOnProvider( const std::vector<FakeDtmfProvider::DtmfInfo>& dtmf_queue_ref) { const std::vector<FakeDtmfProvider::DtmfInfo>& dtmf_queue = provider_->dtmf_info_queue(); ASSERT_EQ(dtmf_queue_ref.size(), dtmf_queue.size()); std::vector<FakeDtmfProvider::DtmfInfo>::const_iterator it_ref = dtmf_queue_ref.begin(); std::vector<FakeDtmfProvider::DtmfInfo>::const_iterator it = dtmf_queue.begin(); while (it_ref != dtmf_queue_ref.end() && it != dtmf_queue.end()) { EXPECT_EQ(it_ref->code, it->code); EXPECT_EQ(it_ref->duration, it->duration); // Allow ~100ms error. EXPECT_GE(it_ref->gap, it->gap - 100); EXPECT_LE(it_ref->gap, it->gap + 100); ++it_ref; ++it; } } // Verify the observer got all the expected callbacks. void VerifyOnObserver(const std::string& tones_ref) { const std::vector<std::string>& tones = observer_->tones(); // The observer will get an empty string at the end. EXPECT_EQ(tones_ref.size() + 1, tones.size()); EXPECT_TRUE(tones.back().empty()); std::string::const_iterator it_ref = tones_ref.begin(); std::vector<std::string>::const_iterator it = tones.begin(); while (it_ref != tones_ref.end() && it != tones.end()) { EXPECT_EQ(*it_ref, it->at(0)); ++it_ref; ++it; } } talk_base::scoped_refptr<AudioTrackInterface> track_; talk_base::scoped_ptr<FakeDtmfObserver> observer_; talk_base::scoped_ptr<FakeDtmfProvider> provider_; talk_base::scoped_refptr<DtmfSender> dtmf_; }; TEST_F(DtmfSenderTest, CanInsertDtmf) { EXPECT_TRUE(dtmf_->CanInsertDtmf()); provider_->RemoveCanInsertDtmfTrack(kTestAudioLabel); EXPECT_FALSE(dtmf_->CanInsertDtmf()); } TEST_F(DtmfSenderTest, InsertDtmf) { std::string tones = "@1%a&*$"; int duration = 100; int inter_tone_gap = 50; EXPECT_TRUE(dtmf_->InsertDtmf(tones, duration, inter_tone_gap)); EXPECT_TRUE_WAIT(observer_->completed(), kMaxWaitMs); // The unrecognized characters should be ignored. std::string known_tones = "1a*"; VerifyOnProvider(known_tones, duration, inter_tone_gap); VerifyOnObserver(known_tones); } TEST_F(DtmfSenderTest, InsertDtmfTwice) { std::string tones1 = "12"; std::string tones2 = "ab"; int duration = 100; int inter_tone_gap = 50; EXPECT_TRUE(dtmf_->InsertDtmf(tones1, duration, inter_tone_gap)); VerifyExpectedState(track_, tones1, duration, inter_tone_gap); // Wait until the first tone got sent. EXPECT_TRUE_WAIT(observer_->tones().size() == 1, kMaxWaitMs); VerifyExpectedState(track_, "2", duration, inter_tone_gap); // Insert with another tone buffer. EXPECT_TRUE(dtmf_->InsertDtmf(tones2, duration, inter_tone_gap)); VerifyExpectedState(track_, tones2, duration, inter_tone_gap); // Wait until it's completed. EXPECT_TRUE_WAIT(observer_->completed(), kMaxWaitMs); std::vector<FakeDtmfProvider::DtmfInfo> dtmf_queue_ref; GetDtmfInfoFromString("1", duration, inter_tone_gap, &dtmf_queue_ref); GetDtmfInfoFromString("ab", duration, inter_tone_gap, &dtmf_queue_ref); VerifyOnProvider(dtmf_queue_ref); VerifyOnObserver("1ab"); } TEST_F(DtmfSenderTest, InsertDtmfWhileProviderIsDeleted) { std::string tones = "@1%a&*$"; int duration = 100; int inter_tone_gap = 50; EXPECT_TRUE(dtmf_->InsertDtmf(tones, duration, inter_tone_gap)); // Wait until the first tone got sent. EXPECT_TRUE_WAIT(observer_->tones().size() == 1, kMaxWaitMs); // Delete provider. provider_.reset(); // The queue should be discontinued so no more tone callbacks. WAIT(false, 200); EXPECT_EQ(1U, observer_->tones().size()); } TEST_F(DtmfSenderTest, InsertDtmfWhileSenderIsDeleted) { std::string tones = "@1%a&*$"; int duration = 100; int inter_tone_gap = 50; EXPECT_TRUE(dtmf_->InsertDtmf(tones, duration, inter_tone_gap)); // Wait until the first tone got sent. EXPECT_TRUE_WAIT(observer_->tones().size() == 1, kMaxWaitMs); // Delete the sender. dtmf_ = NULL; // The queue should be discontinued so no more tone callbacks. WAIT(false, 200); EXPECT_EQ(1U, observer_->tones().size()); } TEST_F(DtmfSenderTest, InsertEmptyTonesToCancelPreviousTask) { std::string tones1 = "12"; std::string tones2 = ""; int duration = 100; int inter_tone_gap = 50; EXPECT_TRUE(dtmf_->InsertDtmf(tones1, duration, inter_tone_gap)); // Wait until the first tone got sent. EXPECT_TRUE_WAIT(observer_->tones().size() == 1, kMaxWaitMs); // Insert with another tone buffer. EXPECT_TRUE(dtmf_->InsertDtmf(tones2, duration, inter_tone_gap)); // Wait until it's completed. EXPECT_TRUE_WAIT(observer_->completed(), kMaxWaitMs); std::vector<FakeDtmfProvider::DtmfInfo> dtmf_queue_ref; GetDtmfInfoFromString("1", duration, inter_tone_gap, &dtmf_queue_ref); VerifyOnProvider(dtmf_queue_ref); VerifyOnObserver("1"); } TEST_F(DtmfSenderTest, InsertDtmfWithCommaAsDelay) { std::string tones = "3,4"; int duration = 100; int inter_tone_gap = 50; EXPECT_TRUE(dtmf_->InsertDtmf(tones, duration, inter_tone_gap)); EXPECT_TRUE_WAIT(observer_->completed(), kMaxWaitMs); VerifyOnProvider(tones, duration, inter_tone_gap); VerifyOnObserver(tones); } TEST_F(DtmfSenderTest, TryInsertDtmfWhenItDoesNotWork) { std::string tones = "3,4"; int duration = 100; int inter_tone_gap = 50; provider_->RemoveCanInsertDtmfTrack(kTestAudioLabel); EXPECT_FALSE(dtmf_->InsertDtmf(tones, duration, inter_tone_gap)); } TEST_F(DtmfSenderTest, InsertDtmfWithInvalidDurationOrGap) { std::string tones = "3,4"; int duration = 100; int inter_tone_gap = 50; EXPECT_FALSE(dtmf_->InsertDtmf(tones, 6001, inter_tone_gap)); EXPECT_FALSE(dtmf_->InsertDtmf(tones, 69, inter_tone_gap)); EXPECT_FALSE(dtmf_->InsertDtmf(tones, duration, 49)); EXPECT_TRUE(dtmf_->InsertDtmf(tones, duration, inter_tone_gap)); } <|endoftext|>
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #ifndef NIX_SECTION_H #define NIX_SECTION_H #include <nix/util/filter.hpp> #include <nix/base/NamedEntity.hpp> #include <nix/base/ISection.hpp> #include <nix/Property.hpp> #include <nix/DataType.hpp> #include <nix/Platform.hpp> #include <memory> #include <functional> #include <string> #include <cstdlib> namespace nix { class Block; class DataArray; class NIXAPI Section : public base::NamedEntity<base::ISection> { public: /** * @brief Constructor that creates an uninitialized Section. * * Calling any method on an uninitialized section will throw a {@link nix::UninitializedEntity} * exception. The following code illustrates how to check if a section is initialized: * * ~~~ * Section e = ...; * if (e) { * // e is initialised * } else { * // e is uninitialized * } * ~~~ */ Section(); /** * @brief Constructor that creates a null Section. */ Section(std::nullptr_t ptr); /** * @brief Copy constructor. * * Copying of all NIX front facing objects like Section is a rather cheap operation. * Semantically this is equivalent to the creation of another reference to the original * object. * * @param other The Section to copy. */ Section(const Section &other); /** * @brief Constructor that creates a new Section from a shared pointer to * an implementation instance. * * This constructor should only be used in the back-end. */ Section(const std::shared_ptr<base::ISection> &p_impl); /** * @brief Constructor with move semantics that creates a new Section from a shared pointer to * an implementation instance. * * This constructor should only be used in the back-end. */ Section(std::shared_ptr<base::ISection> &&ptr); //-------------------------------------------------- // Attribute getter and setter //-------------------------------------------------- /** * @brief Set the repository in which a section of this type is defined. * * Usually this information is provided in the form of an URL * * @param repository URL to the repository. */ void repository(const std::string &repository); /** * @brief Gets the repository URL. * * @return The URL to the repository. */ boost::optional<std::string> repository() const { return backend()->repository(); } /** * @brief Deleter for the repository. * * @param t None */ void repository(const boost::none_t t) { backend()->repository(t); } /** * @brief Establish a link to another section. * * The linking section inherits the properties defined in the linked section. * Properties of the same name are overridden. * * @param id The id of the section that should be linked. */ void link(const std::string &id); /** * @brief Establish a link to another section. * * The linking section inherits the properties defined in the linked section. * Properties of the same name are overridden. * * @param link The section to link with. */ void link(const Section &link); /** * @brief Get the linked section. * * @return The linked section. If no section was linked a null * Section will be returned. */ Section link() const { return backend()->link(); } /** * @brief Deleter for the linked section. * * This just removes the link between both sections, but does not remove * the linked section from the file. * * @param t None */ void link(const boost::none_t t) { backend()->link(t); } /** * @brief Sets the mapping information for this section. * * The mapping is provided as a path or URL to another section. * * @param mapping The mapping information to this section. */ void mapping(const std::string &mapping); /** * @brief Gets the mapping information. * * @return The mapping information. */ boost::optional<std::string> mapping() const { return backend()->mapping(); } /** * @brief Deleter for the mapping information. * * @param t None */ void mapping(const boost::none_t t) { backend()->mapping(t); } //-------------------------------------------------- // Methods for parent access //-------------------------------------------------- /** * @brief Returns the parent section. * * Each section which is not a root section has a parent. * * @return The parent section. If the section has no parent, a null * section will be returned. */ Section parent() const { return backend()->parent(); } //-------------------------------------------------- // Methods for child section access //-------------------------------------------------- /** * @brief Get the number of child section of the section. * * @return The number of child sections. */ ndsize_t sectionCount() const { return backend()->sectionCount(); } /** * @brief Checks whether a section has a certain child section. * * @param name_or_id Name or id of requested section. * * @return True if the section is a child, false otherwise. */ bool hasSection(const std::string &name_or_id) const { return backend()->hasSection(name_or_id); } /** * @brief Checks whether a section has a certain child section. * * @param section The section to check. * * @return True if the section is a child, false otherwise. */ bool hasSection(const Section &section) const; /** * @brief Get a specific child section by its name or id. * * @param name_or_id The name or the ID of the child section. * * @return The child section. */ Section getSection(const std::string &name_or_id) const { return backend()->getSection(name_or_id); } /** * @brief Get a child section by its index. * * @param index The index of the child. * * @return The specified child section. */ virtual Section getSection(ndsize_t index) const; /** * @brief Get all direct child sections of the section. * * The parameter filter can be used to filter sections by various * criteria. By default a filter is used that accepts all sections. * * @param filter A filter function. * * @return A vector containing the matching child sections. */ std::vector<Section> sections(const util::Filter<Section>::type &filter = util::AcceptAll<Section>()) const; /** * @brief Get all descendant sections of the section recursively. * * This method traverses the sub-tree of all child sections of the section. The traversal * is accomplished via breadth first and can be limited in depth. On each node or * section a filter is applied. If the filter returns true the respective section * will be added to the result list. * By default a filter is used that accepts all sections. * * @param filter A filter function. * @param max_depth The maximum depth of traversal. * * @return A vector containing the matching descendant sections. */ std::vector<Section> findSections(const util::Filter<Section>::type &filter = util::AcceptAll<Section>(), size_t max_depth = std::numeric_limits<size_t>::max()) const; /** * @brief Find all related sections of the section. * * @param filter A filter function. * * @return A vector containing all filtered related sections. */ std::vector<Section> findRelated(const util::Filter<Section>::type &filter = util::AcceptAll<Section>()) const; /** * @brief Adds a new child section. * * @param name The name of the new section * @param type The type of the section * * @return The new child section. */ Section createSection(const std::string &name, const std::string &type); /** * @brief Deletes a section from the section. * * @param name_or_id Name or id of the child section to delete. * * @return True if the section was deleted, false otherwise. */ bool deleteSection(const std::string &name_or_id) { return backend()->deleteSection(name_or_id); } /** * @brief Deletes a subsection from this Section. * * @param section The section to delete. * * @return bool successful or not */ bool deleteSection(const Section &section); //-------------------------------------------------- // Methods for property access //-------------------------------------------------- /** * @brief Gets the number of properties of this section. * * @return The number of Properties */ ndsize_t propertyCount() const { return backend()->propertyCount(); } /** * @brief Checks if a Property with this name/id exists in this Section. * * @param name_or_id Name or id of the property. * * @return True if the property exists, false otherwise. */ bool hasProperty(const std::string &name_or_id) const { return backend()->hasProperty(name_or_id); } /** * @brief Checks if a Property exists in this Section. * * @param property The Property to check. * * @return True if the property exists, false otherwise. */ bool hasProperty(const Property &property) const; /** * @brief Gets the Property identified by its name or id. * * @param name_or_id Name or id of the property. * * @return The specified property. */ Property getProperty(const std::string &name_or_id) const { return backend()->getProperty(name_or_id); } /** * @brief Gets the property defined by its index. * * @param index The index of the property * * @return The property. */ Property getProperty(ndsize_t index) const { return backend()->getProperty(index); } /** * @brief Get all properties of the section. * * The parameter filter can be used to filter properties by various * criteria. By default a filter is used that accepts all properties. * * @param filter A filter function. * * @return A vector containing the matching properties. */ std::vector<Property> properties(const util::Filter<Property>::type &filter=util::AcceptAll<Property>()) const; /** * Returns all Properties inherited from a linked section. * This list may include Properties that are locally overridden. * * @return All inherited properties as a vector. */ std::vector<Property> inheritedProperties() const; /** * @brief Add a new Property that does not have any Values to this Section. * * @param name The name of the property. * @param dtype The DataType of the property. * * @return The newly created property */ Property createProperty(const std::string &name, const DataType &dtype); /** * @brief Add a new Property to the Section. * * @param name The name of the property. * @param value The Value to be stored. * * @return The newly created property. */ Property createProperty(const std::string &name, const Value &value); /** * @brief Add a new Property with values to the Section. * * @param name The name of the property. * @param values The values of the created property. * * @return The newly created property. */ Property createProperty(const std::string &name, const std::vector<Value> &values); /** * @brief Delete the Property identified by its name or id. * * @param name_or_id Name or id of the property. * * @return True if the property was deleted, false otherwise. */ bool deleteProperty(const std::string &name_or_id) { return backend()->deleteProperty(name_or_id); } /** * @brief Deletes the Property from this section. * * @param property The Property to delete. * * @return True if the property was deleted, false otherwise. */ bool deleteProperty(const Property &property); //-------------------------------------------------- // Other methods and functions //-------------------------------------------------- std::vector<nix::DataArray> referringDataArrays(const nix::Block & block) const; /** * @brief Assignment operator for none. */ Section &operator=(const none_t &t) { ImplContainer::operator=(t); return *this; } /** * @brief Output operator */ NIXAPI friend std::ostream& operator<<(std::ostream &out, const Section &ent); private: std::vector<Section> findDownstream(const std::function<bool(Section)> &filter) const; std::vector<Section> findUpstream(const std::function<bool(Section)> &filter) const; std::vector<Section> findSideways(const std::function<bool(Section)> &filter, const std::string &caller_id) const; size_t tree_depth() const; }; } // namespace nix #endif // NIX_SECTION_H <commit_msg>[Section] replace forward declarations with nix/types include<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #ifndef NIX_SECTION_H #define NIX_SECTION_H #include <nix/util/filter.hpp> #include <nix/base/NamedEntity.hpp> #include <nix/base/ISection.hpp> #include <nix/Property.hpp> #include <nix/DataType.hpp> #include <nix/Platform.hpp> #include <nix/types.hpp> #include <memory> #include <functional> #include <string> #include <cstdlib> namespace nix { class NIXAPI Section : public base::NamedEntity<base::ISection> { public: /** * @brief Constructor that creates an uninitialized Section. * * Calling any method on an uninitialized section will throw a {@link nix::UninitializedEntity} * exception. The following code illustrates how to check if a section is initialized: * * ~~~ * Section e = ...; * if (e) { * // e is initialised * } else { * // e is uninitialized * } * ~~~ */ Section(); /** * @brief Constructor that creates a null Section. */ Section(std::nullptr_t ptr); /** * @brief Copy constructor. * * Copying of all NIX front facing objects like Section is a rather cheap operation. * Semantically this is equivalent to the creation of another reference to the original * object. * * @param other The Section to copy. */ Section(const Section &other); /** * @brief Constructor that creates a new Section from a shared pointer to * an implementation instance. * * This constructor should only be used in the back-end. */ Section(const std::shared_ptr<base::ISection> &p_impl); /** * @brief Constructor with move semantics that creates a new Section from a shared pointer to * an implementation instance. * * This constructor should only be used in the back-end. */ Section(std::shared_ptr<base::ISection> &&ptr); //-------------------------------------------------- // Attribute getter and setter //-------------------------------------------------- /** * @brief Set the repository in which a section of this type is defined. * * Usually this information is provided in the form of an URL * * @param repository URL to the repository. */ void repository(const std::string &repository); /** * @brief Gets the repository URL. * * @return The URL to the repository. */ boost::optional<std::string> repository() const { return backend()->repository(); } /** * @brief Deleter for the repository. * * @param t None */ void repository(const boost::none_t t) { backend()->repository(t); } /** * @brief Establish a link to another section. * * The linking section inherits the properties defined in the linked section. * Properties of the same name are overridden. * * @param id The id of the section that should be linked. */ void link(const std::string &id); /** * @brief Establish a link to another section. * * The linking section inherits the properties defined in the linked section. * Properties of the same name are overridden. * * @param link The section to link with. */ void link(const Section &link); /** * @brief Get the linked section. * * @return The linked section. If no section was linked a null * Section will be returned. */ Section link() const { return backend()->link(); } /** * @brief Deleter for the linked section. * * This just removes the link between both sections, but does not remove * the linked section from the file. * * @param t None */ void link(const boost::none_t t) { backend()->link(t); } /** * @brief Sets the mapping information for this section. * * The mapping is provided as a path or URL to another section. * * @param mapping The mapping information to this section. */ void mapping(const std::string &mapping); /** * @brief Gets the mapping information. * * @return The mapping information. */ boost::optional<std::string> mapping() const { return backend()->mapping(); } /** * @brief Deleter for the mapping information. * * @param t None */ void mapping(const boost::none_t t) { backend()->mapping(t); } //-------------------------------------------------- // Methods for parent access //-------------------------------------------------- /** * @brief Returns the parent section. * * Each section which is not a root section has a parent. * * @return The parent section. If the section has no parent, a null * section will be returned. */ Section parent() const { return backend()->parent(); } //-------------------------------------------------- // Methods for child section access //-------------------------------------------------- /** * @brief Get the number of child section of the section. * * @return The number of child sections. */ ndsize_t sectionCount() const { return backend()->sectionCount(); } /** * @brief Checks whether a section has a certain child section. * * @param name_or_id Name or id of requested section. * * @return True if the section is a child, false otherwise. */ bool hasSection(const std::string &name_or_id) const { return backend()->hasSection(name_or_id); } /** * @brief Checks whether a section has a certain child section. * * @param section The section to check. * * @return True if the section is a child, false otherwise. */ bool hasSection(const Section &section) const; /** * @brief Get a specific child section by its name or id. * * @param name_or_id The name or the ID of the child section. * * @return The child section. */ Section getSection(const std::string &name_or_id) const { return backend()->getSection(name_or_id); } /** * @brief Get a child section by its index. * * @param index The index of the child. * * @return The specified child section. */ virtual Section getSection(ndsize_t index) const; /** * @brief Get all direct child sections of the section. * * The parameter filter can be used to filter sections by various * criteria. By default a filter is used that accepts all sections. * * @param filter A filter function. * * @return A vector containing the matching child sections. */ std::vector<Section> sections(const util::Filter<Section>::type &filter = util::AcceptAll<Section>()) const; /** * @brief Get all descendant sections of the section recursively. * * This method traverses the sub-tree of all child sections of the section. The traversal * is accomplished via breadth first and can be limited in depth. On each node or * section a filter is applied. If the filter returns true the respective section * will be added to the result list. * By default a filter is used that accepts all sections. * * @param filter A filter function. * @param max_depth The maximum depth of traversal. * * @return A vector containing the matching descendant sections. */ std::vector<Section> findSections(const util::Filter<Section>::type &filter = util::AcceptAll<Section>(), size_t max_depth = std::numeric_limits<size_t>::max()) const; /** * @brief Find all related sections of the section. * * @param filter A filter function. * * @return A vector containing all filtered related sections. */ std::vector<Section> findRelated(const util::Filter<Section>::type &filter = util::AcceptAll<Section>()) const; /** * @brief Adds a new child section. * * @param name The name of the new section * @param type The type of the section * * @return The new child section. */ Section createSection(const std::string &name, const std::string &type); /** * @brief Deletes a section from the section. * * @param name_or_id Name or id of the child section to delete. * * @return True if the section was deleted, false otherwise. */ bool deleteSection(const std::string &name_or_id) { return backend()->deleteSection(name_or_id); } /** * @brief Deletes a subsection from this Section. * * @param section The section to delete. * * @return bool successful or not */ bool deleteSection(const Section &section); //-------------------------------------------------- // Methods for property access //-------------------------------------------------- /** * @brief Gets the number of properties of this section. * * @return The number of Properties */ ndsize_t propertyCount() const { return backend()->propertyCount(); } /** * @brief Checks if a Property with this name/id exists in this Section. * * @param name_or_id Name or id of the property. * * @return True if the property exists, false otherwise. */ bool hasProperty(const std::string &name_or_id) const { return backend()->hasProperty(name_or_id); } /** * @brief Checks if a Property exists in this Section. * * @param property The Property to check. * * @return True if the property exists, false otherwise. */ bool hasProperty(const Property &property) const; /** * @brief Gets the Property identified by its name or id. * * @param name_or_id Name or id of the property. * * @return The specified property. */ Property getProperty(const std::string &name_or_id) const { return backend()->getProperty(name_or_id); } /** * @brief Gets the property defined by its index. * * @param index The index of the property * * @return The property. */ Property getProperty(ndsize_t index) const { return backend()->getProperty(index); } /** * @brief Get all properties of the section. * * The parameter filter can be used to filter properties by various * criteria. By default a filter is used that accepts all properties. * * @param filter A filter function. * * @return A vector containing the matching properties. */ std::vector<Property> properties(const util::Filter<Property>::type &filter=util::AcceptAll<Property>()) const; /** * Returns all Properties inherited from a linked section. * This list may include Properties that are locally overridden. * * @return All inherited properties as a vector. */ std::vector<Property> inheritedProperties() const; /** * @brief Add a new Property that does not have any Values to this Section. * * @param name The name of the property. * @param dtype The DataType of the property. * * @return The newly created property */ Property createProperty(const std::string &name, const DataType &dtype); /** * @brief Add a new Property to the Section. * * @param name The name of the property. * @param value The Value to be stored. * * @return The newly created property. */ Property createProperty(const std::string &name, const Value &value); /** * @brief Add a new Property with values to the Section. * * @param name The name of the property. * @param values The values of the created property. * * @return The newly created property. */ Property createProperty(const std::string &name, const std::vector<Value> &values); /** * @brief Delete the Property identified by its name or id. * * @param name_or_id Name or id of the property. * * @return True if the property was deleted, false otherwise. */ bool deleteProperty(const std::string &name_or_id) { return backend()->deleteProperty(name_or_id); } /** * @brief Deletes the Property from this section. * * @param property The Property to delete. * * @return True if the property was deleted, false otherwise. */ bool deleteProperty(const Property &property); //-------------------------------------------------- // Other methods and functions //-------------------------------------------------- std::vector<nix::DataArray> referringDataArrays(const nix::Block & block) const; /** * @brief Assignment operator for none. */ Section &operator=(const none_t &t) { ImplContainer::operator=(t); return *this; } /** * @brief Output operator */ NIXAPI friend std::ostream& operator<<(std::ostream &out, const Section &ent); private: std::vector<Section> findDownstream(const std::function<bool(Section)> &filter) const; std::vector<Section> findUpstream(const std::function<bool(Section)> &filter) const; std::vector<Section> findSideways(const std::function<bool(Section)> &filter, const std::string &caller_id) const; size_t tree_depth() const; }; } // namespace nix #endif // NIX_SECTION_H <|endoftext|>
<commit_before>#include "framework/serialization/providers/zipdataprovider.h" #include "framework/logger.h" #include "library/sp.h" // Disable automatic #pragma linking for boost - only enabled in msvc and that should provide boost // symbols as part of the module that uses it #define BOOST_ALL_NO_LIB #include "library/strings.h" #include <boost/filesystem.hpp> #include <iostream> namespace fs = boost::filesystem; namespace OpenApoc { ZipDataProvider::ZipDataProvider() : writing(false) { memset(&archive, 0, sizeof(archive)); } ZipDataProvider::~ZipDataProvider() { if (writing) { mz_zip_writer_end(&archive); } else { mz_zip_reader_end(&archive); } } bool ZipDataProvider::openArchive(const UString &path, bool write) { this->zipPath = path; writing = write; if (write) { if (!mz_zip_writer_init_file(&archive, path.cStr(), 0)) { LogWarning("Failed to init zip file \"%s\" for writing", path.cStr()); return false; } } else { if (!mz_zip_reader_init_file(&archive, path.cStr(), 0)) { LogWarning("Failed to init zip file \"%s\" for reading", path.cStr()); return false; } unsigned fileCount = mz_zip_reader_get_num_files(&archive); for (unsigned idx = 0; idx < fileCount; idx++) { unsigned filenameLength = mz_zip_reader_get_filename(&archive, idx, nullptr, 0); up<char[]> data(new char[(unsigned int)filenameLength]); mz_zip_reader_get_filename(&archive, idx, data.get(), filenameLength); std::string filename(data.get()); fileLookup[filename] = idx; } } return true; } bool ZipDataProvider::readDocument(const UString &filename, UString &result) { auto it = fileLookup.find(filename.str()); if (it == fileLookup.end()) { LogInfo("File \"%s\" not found in zip in zip \"%s\"", filename.cStr(), zipPath.cStr()); return false; } unsigned int fileId = it->second; mz_zip_archive_file_stat stat; memset(&stat, 0, sizeof(stat)); if (!mz_zip_reader_file_stat(&archive, fileId, &stat)) { LogWarning("Failed to stat file \"%s\" in zip \"%s\"", filename.cStr(), zipPath.cStr()); return false; } if (stat.m_uncomp_size == 0) { LogInfo("Skipping %s - possibly a directory?", filename.cStr()); return false; } LogInfo("Reading %lu bytes for file \"%s\" in zip \"%s\"", (unsigned long)stat.m_uncomp_size, filename.cStr(), zipPath.cStr()); up<char[]> data(new char[(unsigned int)stat.m_uncomp_size]); if (!mz_zip_reader_extract_to_mem(&archive, fileId, data.get(), (size_t)stat.m_uncomp_size, 0)) { LogWarning("Failed to extract file \"%s\" in zip \"%s\"", filename.cStr(), zipPath.cStr()); return false; } result = std::string(data.get(), (unsigned int)stat.m_uncomp_size); return true; } bool ZipDataProvider::saveDocument(const UString &path, UString contents) { if (!mz_zip_writer_add_mem(&archive, path.cStr(), contents.cStr(), contents.length(), MZ_DEFAULT_COMPRESSION)) { LogWarning("Failed to insert \"%s\" into zip file \"%s\"", path.cStr(), this->zipPath.cStr()); return false; } return true; } bool ZipDataProvider::finalizeSave() { if (writing) { if (!mz_zip_writer_finalize_archive(&archive)) { LogWarning("Failed to finalize archive \"%s\"", zipPath.cStr()); return false; } } return true; } } <commit_msg>Make the zip data provider create parent directories when writing<commit_after>#include "framework/serialization/providers/zipdataprovider.h" #include "framework/logger.h" #include "library/sp.h" // Disable automatic #pragma linking for boost - only enabled in msvc and that should provide boost // symbols as part of the module that uses it #define BOOST_ALL_NO_LIB #include "library/strings.h" #include <boost/filesystem.hpp> #include <iostream> namespace fs = boost::filesystem; namespace OpenApoc { ZipDataProvider::ZipDataProvider() : writing(false) { memset(&archive, 0, sizeof(archive)); } ZipDataProvider::~ZipDataProvider() { if (writing) { mz_zip_writer_end(&archive); } else { mz_zip_reader_end(&archive); } } bool ZipDataProvider::openArchive(const UString &path, bool write) { this->zipPath = path; writing = write; if (write) { auto outPath = fs::path(path.str()); auto outDir = outPath.parent_path(); fs::create_directories(outDir); if (!mz_zip_writer_init_file(&archive, path.cStr(), 0)) { LogWarning("Failed to init zip file \"%s\" for writing", path.cStr()); return false; } } else { if (!mz_zip_reader_init_file(&archive, path.cStr(), 0)) { LogWarning("Failed to init zip file \"%s\" for reading", path.cStr()); return false; } unsigned fileCount = mz_zip_reader_get_num_files(&archive); for (unsigned idx = 0; idx < fileCount; idx++) { unsigned filenameLength = mz_zip_reader_get_filename(&archive, idx, nullptr, 0); up<char[]> data(new char[(unsigned int)filenameLength]); mz_zip_reader_get_filename(&archive, idx, data.get(), filenameLength); std::string filename(data.get()); fileLookup[filename] = idx; } } return true; } bool ZipDataProvider::readDocument(const UString &filename, UString &result) { auto it = fileLookup.find(filename.str()); if (it == fileLookup.end()) { LogInfo("File \"%s\" not found in zip in zip \"%s\"", filename.cStr(), zipPath.cStr()); return false; } unsigned int fileId = it->second; mz_zip_archive_file_stat stat; memset(&stat, 0, sizeof(stat)); if (!mz_zip_reader_file_stat(&archive, fileId, &stat)) { LogWarning("Failed to stat file \"%s\" in zip \"%s\"", filename.cStr(), zipPath.cStr()); return false; } if (stat.m_uncomp_size == 0) { LogInfo("Skipping %s - possibly a directory?", filename.cStr()); return false; } LogInfo("Reading %lu bytes for file \"%s\" in zip \"%s\"", (unsigned long)stat.m_uncomp_size, filename.cStr(), zipPath.cStr()); up<char[]> data(new char[(unsigned int)stat.m_uncomp_size]); if (!mz_zip_reader_extract_to_mem(&archive, fileId, data.get(), (size_t)stat.m_uncomp_size, 0)) { LogWarning("Failed to extract file \"%s\" in zip \"%s\"", filename.cStr(), zipPath.cStr()); return false; } result = std::string(data.get(), (unsigned int)stat.m_uncomp_size); return true; } bool ZipDataProvider::saveDocument(const UString &path, UString contents) { if (!mz_zip_writer_add_mem(&archive, path.cStr(), contents.cStr(), contents.length(), MZ_DEFAULT_COMPRESSION)) { LogWarning("Failed to insert \"%s\" into zip file \"%s\"", path.cStr(), this->zipPath.cStr()); return false; } return true; } bool ZipDataProvider::finalizeSave() { if (writing) { if (!mz_zip_writer_finalize_archive(&archive)) { LogWarning("Failed to finalize archive \"%s\"", zipPath.cStr()); return false; } } return true; } } <|endoftext|>
<commit_before>/* * * Copyright (c) 2021 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /**************************************************************************** * @file * @brief Implementation for the Localization Configuration Server Cluster ***************************************************************************/ #include <app-common/zap-generated/af-structs.h> #include <app-common/zap-generated/attributes/Accessors.h> #include <app-common/zap-generated/cluster-objects.h> #include <app-common/zap-generated/ids/Attributes.h> #include <app-common/zap-generated/ids/Clusters.h> #include <app/AttributeAccessInterface.h> #include <app/util/attribute-storage.h> #include <lib/support/CodeUtils.h> #include <lib/support/logging/CHIPLogging.h> #include <platform/PlatformManager.h> using namespace chip; using namespace chip::app; using namespace chip::app::Clusters; using namespace chip::app::Clusters::LocalizationConfiguration; using namespace chip::app::Clusters::LocalizationConfiguration::Attributes; namespace { class LocalizationConfigurationAttrAccess : public AttributeAccessInterface { public: // Register for the Localization Configuration cluster on all endpoints. LocalizationConfigurationAttrAccess() : AttributeAccessInterface(Optional<EndpointId>::Missing(), LocalizationConfiguration::Id) {} CHIP_ERROR Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) override; private: CHIP_ERROR ReadSupportedLocales(AttributeValueEncoder & aEncoder); }; LocalizationConfigurationAttrAccess gAttrAccess; CHIP_ERROR LocalizationConfigurationAttrAccess::ReadSupportedLocales(AttributeValueEncoder & aEncoder) { CHIP_ERROR err = CHIP_NO_ERROR; DeviceLayer::AttributeList<CharSpan, DeviceLayer::kMaxLanguageTags> supportedLocales; if (DeviceLayer::PlatformMgr().GetSupportedLocales(supportedLocales) == CHIP_NO_ERROR) { err = aEncoder.EncodeList([&supportedLocales](const auto & encoder) -> CHIP_ERROR { for (const Span<const char> & locale : supportedLocales) { ReturnErrorOnFailure(encoder.Encode(locale)); } return CHIP_NO_ERROR; }); } else { err = aEncoder.EncodeEmptyList(); } return err; } CHIP_ERROR LocalizationConfigurationAttrAccess::Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) { VerifyOrDie(aPath.mClusterId == LocalizationConfiguration::Id); switch (aPath.mAttributeId) { case SupportedLocales::Id: return ReadSupportedLocales(aEncoder); default: break; } return CHIP_NO_ERROR; } } // anonymous namespace // ============================================================================= // Pre-change callbacks for cluster attributes // ============================================================================= static Protocols::InteractionModel::Status emberAfPluginLocalizationConfigurationOnActiveLocaleChange(EndpointId EndpointId, CharSpan newLangtag) { DeviceLayer::AttributeList<CharSpan, DeviceLayer::kMaxLanguageTags> supportedLocales; if (DeviceLayer::PlatformMgr().GetSupportedLocales(supportedLocales) == CHIP_NO_ERROR) { for (const Span<const char> & locale : supportedLocales) { if (locale.data_equal(newLangtag)) { return Protocols::InteractionModel::Status::Success; } } } return Protocols::InteractionModel::Status::InvalidValue; } static Protocols::InteractionModel::Status emberAfPluginLocalizationConfigurationOnUnhandledAttributeChange(EndpointId EndpointId, EmberAfAttributeType attrType, uint16_t attrSize, uint8_t * attrValue) { return Protocols::InteractionModel::Status::Success; } Protocols::InteractionModel::Status MatterLocalizationConfigurationClusterServerPreAttributeChangedCallback( const ConcreteAttributePath & attributePath, EmberAfAttributeType attributeType, uint16_t size, uint8_t * value) { Protocols::InteractionModel::Status res; switch (attributePath.mAttributeId) { case ActiveLocale::Id: { // TODO:: allow fromZclString for CharSpan as well and use that here auto langtag = CharSpan(Uint8::to_char(&value[1]), static_cast<size_t>(value[0])); res = emberAfPluginLocalizationConfigurationOnActiveLocaleChange(attributePath.mEndpointId, langtag); } break; default: res = emberAfPluginLocalizationConfigurationOnUnhandledAttributeChange(attributePath.mEndpointId, attributeType, size, value); break; } return res; } void emberAfLocalizationConfigurationClusterServerInitCallback(EndpointId endpoint) { DeviceLayer::AttributeList<CharSpan, DeviceLayer::kMaxLanguageTags> supportedLocales; CharSpan validLocale; char outBuffer[Attributes::ActiveLocale::TypeInfo::MaxLength()]; MutableCharSpan activeLocale(outBuffer); EmberAfStatus status = ActiveLocale::Get(endpoint, activeLocale); VerifyOrReturn(EMBER_ZCL_STATUS_SUCCESS == status, ChipLogError(Zcl, "Failed to read ActiveLocale with error: 0x%02x", status)); // We could have an invalid ActiveLocale value if an OTA update removed support for the value we were using. if (DeviceLayer::PlatformMgr().GetSupportedLocales(supportedLocales) == CHIP_NO_ERROR) { for (const Span<const char> & locale : supportedLocales) { if (locale.data_equal(activeLocale)) { return; } validLocale = locale; } // If initial value is not one of the allowed values, pick one valid value and write it. status = ActiveLocale::Set(endpoint, validLocale); VerifyOrReturn(EMBER_ZCL_STATUS_SUCCESS == status, ChipLogError(Zcl, "Failed to write active locale with error: 0x%02x", status)); } } void MatterLocalizationConfigurationPluginServerInitCallback(void) { registerAttributeAccessOverride(&gAttrAccess); } <commit_msg>Cleanup redundant helper function in localization configuration server (#15744)<commit_after>/* * * Copyright (c) 2021 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /**************************************************************************** * @file * @brief Implementation for the Localization Configuration Server Cluster ***************************************************************************/ #include <app-common/zap-generated/af-structs.h> #include <app-common/zap-generated/attributes/Accessors.h> #include <app-common/zap-generated/cluster-objects.h> #include <app-common/zap-generated/ids/Attributes.h> #include <app-common/zap-generated/ids/Clusters.h> #include <app/AttributeAccessInterface.h> #include <app/util/attribute-storage.h> #include <lib/support/CodeUtils.h> #include <lib/support/logging/CHIPLogging.h> #include <platform/PlatformManager.h> using namespace chip; using namespace chip::app; using namespace chip::app::Clusters; using namespace chip::app::Clusters::LocalizationConfiguration; using namespace chip::app::Clusters::LocalizationConfiguration::Attributes; namespace { class LocalizationConfigurationAttrAccess : public AttributeAccessInterface { public: // Register for the Localization Configuration cluster on all endpoints. LocalizationConfigurationAttrAccess() : AttributeAccessInterface(Optional<EndpointId>::Missing(), LocalizationConfiguration::Id) {} CHIP_ERROR Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) override; private: CHIP_ERROR ReadSupportedLocales(AttributeValueEncoder & aEncoder); }; LocalizationConfigurationAttrAccess gAttrAccess; CHIP_ERROR LocalizationConfigurationAttrAccess::ReadSupportedLocales(AttributeValueEncoder & aEncoder) { CHIP_ERROR err = CHIP_NO_ERROR; DeviceLayer::AttributeList<CharSpan, DeviceLayer::kMaxLanguageTags> supportedLocales; if (DeviceLayer::PlatformMgr().GetSupportedLocales(supportedLocales) == CHIP_NO_ERROR) { err = aEncoder.EncodeList([&supportedLocales](const auto & encoder) -> CHIP_ERROR { for (const Span<const char> & locale : supportedLocales) { ReturnErrorOnFailure(encoder.Encode(locale)); } return CHIP_NO_ERROR; }); } else { err = aEncoder.EncodeEmptyList(); } return err; } CHIP_ERROR LocalizationConfigurationAttrAccess::Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) { VerifyOrDie(aPath.mClusterId == LocalizationConfiguration::Id); switch (aPath.mAttributeId) { case SupportedLocales::Id: return ReadSupportedLocales(aEncoder); default: break; } return CHIP_NO_ERROR; } } // anonymous namespace // ============================================================================= // Pre-change callbacks for cluster attributes // ============================================================================= using Status = Protocols::InteractionModel::Status; static Protocols::InteractionModel::Status emberAfPluginLocalizationConfigurationOnActiveLocaleChange(EndpointId EndpointId, CharSpan newLangtag) { DeviceLayer::AttributeList<CharSpan, DeviceLayer::kMaxLanguageTags> supportedLocales; if (DeviceLayer::PlatformMgr().GetSupportedLocales(supportedLocales) == CHIP_NO_ERROR) { for (const Span<const char> & locale : supportedLocales) { if (locale.data_equal(newLangtag)) { return Status::Success; } } } return Status::InvalidValue; } Protocols::InteractionModel::Status MatterLocalizationConfigurationClusterServerPreAttributeChangedCallback( const ConcreteAttributePath & attributePath, EmberAfAttributeType attributeType, uint16_t size, uint8_t * value) { Protocols::InteractionModel::Status res; switch (attributePath.mAttributeId) { case ActiveLocale::Id: { // TODO:: allow fromZclString for CharSpan as well and use that here auto langtag = CharSpan(Uint8::to_char(&value[1]), static_cast<size_t>(value[0])); res = emberAfPluginLocalizationConfigurationOnActiveLocaleChange(attributePath.mEndpointId, langtag); break; } default: res = Status::Success; break; } return res; } void emberAfLocalizationConfigurationClusterServerInitCallback(EndpointId endpoint) { DeviceLayer::AttributeList<CharSpan, DeviceLayer::kMaxLanguageTags> supportedLocales; CharSpan validLocale; char outBuffer[Attributes::ActiveLocale::TypeInfo::MaxLength()]; MutableCharSpan activeLocale(outBuffer); EmberAfStatus status = ActiveLocale::Get(endpoint, activeLocale); VerifyOrReturn(EMBER_ZCL_STATUS_SUCCESS == status, ChipLogError(Zcl, "Failed to read ActiveLocale with error: 0x%02x", status)); // We could have an invalid ActiveLocale value if an OTA update removed support for the value we were using. if (DeviceLayer::PlatformMgr().GetSupportedLocales(supportedLocales) == CHIP_NO_ERROR) { for (const Span<const char> & locale : supportedLocales) { if (locale.data_equal(activeLocale)) { return; } validLocale = locale; } // If initial value is not one of the allowed values, pick one valid value and write it. status = ActiveLocale::Set(endpoint, validLocale); VerifyOrReturn(EMBER_ZCL_STATUS_SUCCESS == status, ChipLogError(Zcl, "Failed to write active locale with error: 0x%02x", status)); } } void MatterLocalizationConfigurationPluginServerInitCallback(void) { registerAttributeAccessOverride(&gAttrAccess); } <|endoftext|>
<commit_before>/* The Next Great Finite Element Library. */ /* Copyright (C) 2003 Benjamin S. Kirk */ /* This library is free software; you can redistribute it and/or */ /* modify it under the terms of the GNU Lesser General Public */ /* License as published by the Free Software Foundation; either */ /* version 2.1 of the License, or (at your option) any later version. */ /* This library is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */ /* Lesser General Public License for more details. */ /* You should have received a copy of the GNU Lesser General Public */ /* License along with this library; if not, write to the Free Software */ /* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // <h1>Example 5 - Run-Time Quadrature Rule Selection</h1> // // This is the fifth example program. It builds on // the previous two examples, and extends the use // of the \p AutoPtr as a convenient build method to // determine the quadrature rule at run time. // C++ include files that we need #include <iostream> #include <sstream> #include <algorithm> #include <math.h> // Basic include file needed for the mesh functionality. #include "libmesh.h" #include "mesh.h" #include "mesh_generation.h" #include "exodusII_io.h" #include "linear_implicit_system.h" #include "equation_systems.h" // Define the Finite Element object. #include "fe.h" // Define the base quadrature class, with which // specialized quadrature rules will be built. #include "quadrature.h" // Include the namespace \p QuadratureRules for // some handy descriptions. #include "quadrature_rules.h" // Define useful datatypes for finite element // matrix and vector components. #include "sparse_matrix.h" #include "numeric_vector.h" #include "dense_matrix.h" #include "dense_vector.h" // Define the DofMap, which handles degree of freedom // indexing. #include "dof_map.h" // The definition of a geometric element #include "elem.h" // Bring in everything from the libMesh namespace using namespace libMesh; // Function prototype, as before. void assemble_poisson(EquationSystems& es, const std::string& system_name); // Exact solution function prototype, as before. Real exact_solution (const Real x, const Real y, const Real z = 0.); // The quadrature type the user requests. QuadratureType quad_type=INVALID_Q_RULE; // Begin the main program. int main (int argc, char** argv) { // Initialize libMesh and any dependent libaries, like in example 2. LibMeshInit init (argc, argv); // Check for proper usage. The quadrature rule // must be given at run time. if (argc < 3) { if (libMesh::processor_id() == 0) { std::cerr << "Usage: " << argv[0] << " -q n" << std::endl; std::cerr << " where n stands for:" << std::endl; // Note that only some of all quadrature rules are // valid choices. For example, the Jacobi quadrature // is actually a "helper" for higher-order rules, // included in QGauss. for (unsigned int n=0; n<QuadratureRules::num_valid_elem_rules; n++) std::cerr << " " << QuadratureRules::valid_elem_rules[n] << " " << QuadratureRules::name(QuadratureRules::valid_elem_rules[n]) << std::endl; std::cerr << std::endl; } libmesh_error(); } // Tell the user what we are doing. else { std::cout << "Running " << argv[0]; for (int i=1; i<argc; i++) std::cout << " " << argv[i]; std::cout << std::endl << std::endl; } // Set the quadrature rule type that the user wants from argv[2] quad_type = static_cast<QuadratureType>(std::atoi(argv[2])); // Skip this 3D example if libMesh was compiled as 1D-only. libmesh_example_assert(3 <= LIBMESH_DIM, "3D support"); // The following is identical to example 4, and therefore // not commented. Differences are mentioned when present. Mesh mesh; // We will use a linear approximation space in this example, // hence 8-noded hexahedral elements are sufficient. This // is different than example 4 where we used 27-noded // hexahedral elements to support a second-order approximation // space. MeshTools::Generation::build_cube (mesh, 16, 16, 16, -1., 1., -1., 1., -1., 1., HEX8); mesh.print_info(); EquationSystems equation_systems (mesh); equation_systems.add_system<LinearImplicitSystem> ("Poisson"); equation_systems.get_system("Poisson").add_variable("u", FIRST); equation_systems.get_system("Poisson").attach_assemble_function (assemble_poisson); equation_systems.init(); equation_systems.print_info(); equation_systems.get_system("Poisson").solve(); // "Personalize" the output, with the // number of the quadrature rule appended. std::ostringstream f_name; f_name << "out_" << quad_type << ".e"; #ifdef LIBMESH_HAVE_EXODUS_API ExodusII_IO(mesh).write_equation_systems (f_name.str(), equation_systems); #endif // #ifdef LIBMESH_HAVE_EXODUS_API // All done. return 0; } void assemble_poisson(EquationSystems& es, const std::string& system_name) { libmesh_assert (system_name == "Poisson"); const MeshBase& mesh = es.get_mesh(); const unsigned int dim = mesh.mesh_dimension(); LinearImplicitSystem& system = es.get_system<LinearImplicitSystem>("Poisson"); const DofMap& dof_map = system.get_dof_map(); FEType fe_type = dof_map.variable_type(0); // Build a Finite Element object of the specified type. Since the // \p FEBase::build() member dynamically creates memory we will // store the object as an \p AutoPtr<FEBase>. Below, the // functionality of \p AutoPtr's is described more detailed in // the context of building quadrature rules. AutoPtr<FEBase> fe (FEBase::build(dim, fe_type)); // Now this deviates from example 4. we create a // 5th order quadrature rule of user-specified type // for numerical integration. Note that not all // quadrature rules support this order. AutoPtr<QBase> qrule(QBase::build(quad_type, dim, THIRD)); // Tell the finte element object to use our // quadrature rule. Note that a \p AutoPtr<QBase> returns // a QBase* pointer to the object it handles with \p get(). // However, using \p get(), the \p AutoPtr<QBase> \p qrule is // still in charge of this pointer. I.e., when \p qrule goes // out of scope, it will safely delete the \p QBase object it // points to. This behavior may be overridden using // \p AutoPtr<Xyz>::release(), but is currently not // recommended. fe->attach_quadrature_rule (qrule.get()); // Declare a special finite element object for // boundary integration. AutoPtr<FEBase> fe_face (FEBase::build(dim, fe_type)); // As already seen in example 3, boundary integration // requires a quadrature rule. Here, however, // we use the more convenient way of building this // rule at run-time using \p quad_type. Note that one // could also have initialized the face quadrature rules // with the type directly determined from \p qrule, namely // through: // \verbatim // AutoPtr<QBase> qface (QBase::build(qrule->type(), // dim-1, // THIRD)); // \endverbatim // And again: using the \p AutoPtr<QBase> relaxes // the need to delete the object afterwards, // they clean up themselves. AutoPtr<QBase> qface (QBase::build(quad_type, dim-1, THIRD)); // Tell the finte element object to use our // quadrature rule. Note that a \p AutoPtr<QBase> returns // a \p QBase* pointer to the object it handles with \p get(). // However, using \p get(), the \p AutoPtr<QBase> \p qface is // still in charge of this pointer. I.e., when \p qface goes // out of scope, it will safely delete the \p QBase object it // points to. This behavior may be overridden using // \p AutoPtr<Xyz>::release(), but is not recommended. fe_face->attach_quadrature_rule (qface.get()); // This is again identical to example 4, and not commented. const std::vector<Real>& JxW = fe->get_JxW(); const std::vector<Point>& q_point = fe->get_xyz(); const std::vector<std::vector<Real> >& phi = fe->get_phi(); const std::vector<std::vector<RealGradient> >& dphi = fe->get_dphi(); DenseMatrix<Number> Ke; DenseVector<Number> Fe; std::vector<unsigned int> dof_indices; // Now we will loop over all the elements in the mesh. // See example 3 for details. MeshBase::const_element_iterator el = mesh.active_local_elements_begin(); const MeshBase::const_element_iterator end_el = mesh.active_local_elements_end(); for ( ; el != end_el; ++el) { const Elem* elem = *el; dof_map.dof_indices (elem, dof_indices); fe->reinit (elem); Ke.resize (dof_indices.size(), dof_indices.size()); Fe.resize (dof_indices.size()); // Now loop over the quadrature points. This handles // the numeric integration. Note the slightly different // access to the QBase members! for (unsigned int qp=0; qp<qrule->n_points(); qp++) { // Add the matrix contribution for (unsigned int i=0; i<phi.size(); i++) for (unsigned int j=0; j<phi.size(); j++) Ke(i,j) += JxW[qp]*(dphi[i][qp]*dphi[j][qp]); // fxy is the forcing function for the Poisson equation. // In this case we set fxy to be a finite difference // Laplacian approximation to the (known) exact solution. // // We will use the second-order accurate FD Laplacian // approximation, which in 2D on a structured grid is // // u_xx + u_yy = (u(i-1,j) + u(i+1,j) + // u(i,j-1) + u(i,j+1) + // -4*u(i,j))/h^2 // // Since the value of the forcing function depends only // on the location of the quadrature point (q_point[qp]) // we will compute it here, outside of the i-loop const Real x = q_point[qp](0); const Real y = q_point[qp](1); const Real z = q_point[qp](2); const Real eps = 1.e-3; const Real uxx = (exact_solution(x-eps,y,z) + exact_solution(x+eps,y,z) + -2.*exact_solution(x,y,z))/eps/eps; const Real uyy = (exact_solution(x,y-eps,z) + exact_solution(x,y+eps,z) + -2.*exact_solution(x,y,z))/eps/eps; const Real uzz = (exact_solution(x,y,z-eps) + exact_solution(x,y,z+eps) + -2.*exact_solution(x,y,z))/eps/eps; const Real fxy = - (uxx + uyy + ((dim==2) ? 0. : uzz)); // Add the RHS contribution for (unsigned int i=0; i<phi.size(); i++) Fe(i) += JxW[qp]*fxy*phi[i][qp]; } // Most of this has already been seen before, except // for the build routines of QBase, described below { for (unsigned int side=0; side<elem->n_sides(); side++) if (elem->neighbor(side) == NULL) { const std::vector<std::vector<Real> >& phi_face = fe_face->get_phi(); const std::vector<Real>& JxW_face = fe_face->get_JxW(); const std::vector<Point >& qface_point = fe_face->get_xyz(); // Compute the shape function values on the element // face. fe_face->reinit(elem, side); // Loop over the face quadrature points for integration. // Note that the \p AutoPtr<QBase> overloaded the operator->, // so that QBase methods may safely be accessed. It may // be said: accessing an \p AutoPtr<Xyz> through the // "." operator returns \p AutoPtr methods, while access // through the "->" operator returns Xyz methods. // This allows almost no change in syntax when switching // to "safe pointers". for (unsigned int qp=0; qp<qface->n_points(); qp++) { const Real xf = qface_point[qp](0); const Real yf = qface_point[qp](1); const Real zf = qface_point[qp](2); const Real penalty = 1.e10; const Real value = exact_solution(xf, yf, zf); for (unsigned int i=0; i<phi_face.size(); i++) for (unsigned int j=0; j<phi_face.size(); j++) Ke(i,j) += JxW_face[qp]*penalty*phi_face[i][qp]*phi_face[j][qp]; for (unsigned int i=0; i<phi_face.size(); i++) Fe(i) += JxW_face[qp]*penalty*value*phi_face[i][qp]; } // end face quadrature point loop } // end if (elem->neighbor(side) == NULL) } // end boundary condition section // If this assembly program were to be used on an adaptive mesh, // we would have to apply any hanging node constraint equations dof_map.constrain_element_matrix_and_vector (Ke, Fe, dof_indices); // The element matrix and right-hand-side are now built // for this element. Add them to the global matrix and // right-hand-side vector. The \p SparseMatrix::add_matrix() // and \p NumericVector::add_vector() members do this for us. system.matrix->add_matrix (Ke, dof_indices); system.rhs->add_vector (Fe, dof_indices); } // end of element loop // All done! return; } <commit_msg>Modified introduction_ex5 to use DirichletBoundary instead of a penalty approach<commit_after>/* The Next Great Finite Element Library. */ /* Copyright (C) 2003 Benjamin S. Kirk */ /* This library is free software; you can redistribute it and/or */ /* modify it under the terms of the GNU Lesser General Public */ /* License as published by the Free Software Foundation; either */ /* version 2.1 of the License, or (at your option) any later version. */ /* This library is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */ /* Lesser General Public License for more details. */ /* You should have received a copy of the GNU Lesser General Public */ /* License along with this library; if not, write to the Free Software */ /* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // <h1>Example 5 - Run-Time Quadrature Rule Selection</h1> // // This is the fifth example program. It builds on // the previous two examples, and extends the use // of the \p AutoPtr as a convenient build method to // determine the quadrature rule at run time. // C++ include files that we need #include <iostream> #include <sstream> #include <algorithm> #include <math.h> // Basic include file needed for the mesh functionality. #include "libmesh.h" #include "mesh.h" #include "mesh_generation.h" #include "exodusII_io.h" #include "linear_implicit_system.h" #include "equation_systems.h" // Define the Finite Element object. #include "fe.h" // Define the base quadrature class, with which // specialized quadrature rules will be built. #include "quadrature.h" // Include the namespace \p QuadratureRules for // some handy descriptions. #include "quadrature_rules.h" // Define useful datatypes for finite element // matrix and vector components. #include "sparse_matrix.h" #include "numeric_vector.h" #include "dense_matrix.h" #include "dense_vector.h" // Define the DofMap, which handles degree of freedom // indexing. #include "dof_map.h" // To impose Dirichlet boundary conditions #include "dirichlet_boundaries.h" #include "analytic_function.h" // The definition of a geometric element #include "elem.h" // Bring in everything from the libMesh namespace using namespace libMesh; // Function prototype, as before. void assemble_poisson(EquationSystems& es, const std::string& system_name); // Exact solution function prototype, as before. Real exact_solution (const Real x, const Real y, const Real z = 0.); // Define a wrapper for exact_solution that will be needed below void exact_solution_wrapper (DenseVector<Number>& output, const Point& p, const Real) { output(0) = exact_solution(p(0),p(1),p(2)); } // The quadrature type the user requests. QuadratureType quad_type=INVALID_Q_RULE; // Begin the main program. int main (int argc, char** argv) { // Initialize libMesh and any dependent libaries, like in example 2. LibMeshInit init (argc, argv); // Check for proper usage. The quadrature rule // must be given at run time. if (argc < 3) { if (libMesh::processor_id() == 0) { std::cerr << "Usage: " << argv[0] << " -q n" << std::endl; std::cerr << " where n stands for:" << std::endl; // Note that only some of all quadrature rules are // valid choices. For example, the Jacobi quadrature // is actually a "helper" for higher-order rules, // included in QGauss. for (unsigned int n=0; n<QuadratureRules::num_valid_elem_rules; n++) std::cerr << " " << QuadratureRules::valid_elem_rules[n] << " " << QuadratureRules::name(QuadratureRules::valid_elem_rules[n]) << std::endl; std::cerr << std::endl; } libmesh_error(); } // Tell the user what we are doing. else { std::cout << "Running " << argv[0]; for (int i=1; i<argc; i++) std::cout << " " << argv[i]; std::cout << std::endl << std::endl; } // Set the quadrature rule type that the user wants from argv[2] quad_type = static_cast<QuadratureType>(std::atoi(argv[2])); // Skip this 3D example if libMesh was compiled as 1D-only. libmesh_example_assert(3 <= LIBMESH_DIM, "3D support"); // The following is identical to example 4, and therefore // not commented. Differences are mentioned when present. Mesh mesh; // We will use a linear approximation space in this example, // hence 8-noded hexahedral elements are sufficient. This // is different than example 4 where we used 27-noded // hexahedral elements to support a second-order approximation // space. MeshTools::Generation::build_cube (mesh, 16, 16, 16, -1., 1., -1., 1., -1., 1., HEX8); mesh.print_info(); EquationSystems equation_systems (mesh); equation_systems.add_system<LinearImplicitSystem> ("Poisson"); unsigned int u_var = equation_systems.get_system("Poisson").add_variable("u", FIRST); equation_systems.get_system("Poisson").attach_assemble_function (assemble_poisson); // Construct a Dirichlet boundary condition object // Indicate which boundary IDs we impose the BC on // We either build a line, a square or a cube, and // here we indicate the boundaries IDs in each case std::set<boundary_id_type> boundary_ids; // the dim==1 mesh has two boundaries with IDs 0 and 1 boundary_ids.insert(0); boundary_ids.insert(1); boundary_ids.insert(2); boundary_ids.insert(3); boundary_ids.insert(4); boundary_ids.insert(5); // Create a vector storing the variable numbers which the BC applies to std::vector<unsigned int> variables(1); variables[0] = u_var; // Create an AnalyticFunction object that we use to project the BC // This function just calls the function exact_solution via exact_solution_wrapper AnalyticFunction<> exact_solution_object(exact_solution_wrapper); DirichletBoundary dirichlet_bc(boundary_ids, variables, &exact_solution_object); // We must add the Dirichlet boundary condition _before_ // we call equation_systems.init() equation_systems.get_system("Poisson").get_dof_map().add_dirichlet_boundary(dirichlet_bc); equation_systems.init(); equation_systems.print_info(); equation_systems.get_system("Poisson").solve(); // "Personalize" the output, with the // number of the quadrature rule appended. std::ostringstream f_name; f_name << "out_" << quad_type << ".e"; #ifdef LIBMESH_HAVE_EXODUS_API ExodusII_IO(mesh).write_equation_systems (f_name.str(), equation_systems); #endif // #ifdef LIBMESH_HAVE_EXODUS_API // All done. return 0; } void assemble_poisson(EquationSystems& es, const std::string& system_name) { libmesh_assert (system_name == "Poisson"); const MeshBase& mesh = es.get_mesh(); const unsigned int dim = mesh.mesh_dimension(); LinearImplicitSystem& system = es.get_system<LinearImplicitSystem>("Poisson"); const DofMap& dof_map = system.get_dof_map(); FEType fe_type = dof_map.variable_type(0); // Build a Finite Element object of the specified type. Since the // \p FEBase::build() member dynamically creates memory we will // store the object as an \p AutoPtr<FEBase>. Below, the // functionality of \p AutoPtr's is described more detailed in // the context of building quadrature rules. AutoPtr<FEBase> fe (FEBase::build(dim, fe_type)); // Now this deviates from example 4. we create a // 5th order quadrature rule of user-specified type // for numerical integration. Note that not all // quadrature rules support this order. AutoPtr<QBase> qrule(QBase::build(quad_type, dim, THIRD)); // Tell the finte element object to use our // quadrature rule. Note that a \p AutoPtr<QBase> returns // a QBase* pointer to the object it handles with \p get(). // However, using \p get(), the \p AutoPtr<QBase> \p qrule is // still in charge of this pointer. I.e., when \p qrule goes // out of scope, it will safely delete the \p QBase object it // points to. This behavior may be overridden using // \p AutoPtr<Xyz>::release(), but is currently not // recommended. fe->attach_quadrature_rule (qrule.get()); // Declare a special finite element object for // boundary integration. AutoPtr<FEBase> fe_face (FEBase::build(dim, fe_type)); // As already seen in example 3, boundary integration // requires a quadrature rule. Here, however, // we use the more convenient way of building this // rule at run-time using \p quad_type. Note that one // could also have initialized the face quadrature rules // with the type directly determined from \p qrule, namely // through: // \verbatim // AutoPtr<QBase> qface (QBase::build(qrule->type(), // dim-1, // THIRD)); // \endverbatim // And again: using the \p AutoPtr<QBase> relaxes // the need to delete the object afterwards, // they clean up themselves. AutoPtr<QBase> qface (QBase::build(quad_type, dim-1, THIRD)); // Tell the finte element object to use our // quadrature rule. Note that a \p AutoPtr<QBase> returns // a \p QBase* pointer to the object it handles with \p get(). // However, using \p get(), the \p AutoPtr<QBase> \p qface is // still in charge of this pointer. I.e., when \p qface goes // out of scope, it will safely delete the \p QBase object it // points to. This behavior may be overridden using // \p AutoPtr<Xyz>::release(), but is not recommended. fe_face->attach_quadrature_rule (qface.get()); // This is again identical to example 4, and not commented. const std::vector<Real>& JxW = fe->get_JxW(); const std::vector<Point>& q_point = fe->get_xyz(); const std::vector<std::vector<Real> >& phi = fe->get_phi(); const std::vector<std::vector<RealGradient> >& dphi = fe->get_dphi(); DenseMatrix<Number> Ke; DenseVector<Number> Fe; std::vector<unsigned int> dof_indices; // Now we will loop over all the elements in the mesh. // See example 3 for details. MeshBase::const_element_iterator el = mesh.active_local_elements_begin(); const MeshBase::const_element_iterator end_el = mesh.active_local_elements_end(); for ( ; el != end_el; ++el) { const Elem* elem = *el; dof_map.dof_indices (elem, dof_indices); fe->reinit (elem); Ke.resize (dof_indices.size(), dof_indices.size()); Fe.resize (dof_indices.size()); // Now loop over the quadrature points. This handles // the numeric integration. Note the slightly different // access to the QBase members! for (unsigned int qp=0; qp<qrule->n_points(); qp++) { // Add the matrix contribution for (unsigned int i=0; i<phi.size(); i++) for (unsigned int j=0; j<phi.size(); j++) Ke(i,j) += JxW[qp]*(dphi[i][qp]*dphi[j][qp]); // fxy is the forcing function for the Poisson equation. // In this case we set fxy to be a finite difference // Laplacian approximation to the (known) exact solution. // // We will use the second-order accurate FD Laplacian // approximation, which in 2D on a structured grid is // // u_xx + u_yy = (u(i-1,j) + u(i+1,j) + // u(i,j-1) + u(i,j+1) + // -4*u(i,j))/h^2 // // Since the value of the forcing function depends only // on the location of the quadrature point (q_point[qp]) // we will compute it here, outside of the i-loop const Real x = q_point[qp](0); const Real y = q_point[qp](1); const Real z = q_point[qp](2); const Real eps = 1.e-3; const Real uxx = (exact_solution(x-eps,y,z) + exact_solution(x+eps,y,z) + -2.*exact_solution(x,y,z))/eps/eps; const Real uyy = (exact_solution(x,y-eps,z) + exact_solution(x,y+eps,z) + -2.*exact_solution(x,y,z))/eps/eps; const Real uzz = (exact_solution(x,y,z-eps) + exact_solution(x,y,z+eps) + -2.*exact_solution(x,y,z))/eps/eps; const Real fxy = - (uxx + uyy + ((dim==2) ? 0. : uzz)); // Add the RHS contribution for (unsigned int i=0; i<phi.size(); i++) Fe(i) += JxW[qp]*fxy*phi[i][qp]; } // If this assembly program were to be used on an adaptive mesh, // we would have to apply any hanging node constraint equations // Call heterogenously_constrain_element_matrix_and_vector to impose // non-homogeneous Dirichlet BCs dof_map.heterogenously_constrain_element_matrix_and_vector (Ke, Fe, dof_indices); // The element matrix and right-hand-side are now built // for this element. Add them to the global matrix and // right-hand-side vector. The \p SparseMatrix::add_matrix() // and \p NumericVector::add_vector() members do this for us. system.matrix->add_matrix (Ke, dof_indices); system.rhs->add_vector (Fe, dof_indices); } // end of element loop // All done! return; } <|endoftext|>
<commit_before>//============================================================================== // CellML annotation view CellML details widget //============================================================================== #include "borderedwidget.h" #include "cellmlannotationviewcellmldetailswidget.h" #include "cellmlannotationviewmetadatabiomodelsdotnetviewdetailswidget.h" #include "cellmlannotationviewwidget.h" #include "cellmlannotationviewmetadataviewdetailswidget.h" #include "coreutils.h" //============================================================================== #include "ui_cellmlannotationviewcellmldetailswidget.h" //============================================================================== #include <QComboBox> #include <QFile> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> #include <QWebView> //============================================================================== #include <QJsonParser> //============================================================================== namespace OpenCOR { namespace CellMLAnnotationView { //============================================================================== CellmlAnnotationViewCellmlDetailsWidget::CellmlAnnotationViewCellmlDetailsWidget(CellmlAnnotationViewWidget *pParent) : QSplitter(pParent), CommonWidget(pParent), mParent(pParent), mGui(new Ui::CellmlAnnotationViewCellmlDetailsWidget) { // Set up the GUI mGui->setupUi(this); // Create our details widgets mCellmlElementDetails = new CellmlAnnotationViewCellmlElementDetailsWidget(pParent); mMetadataViewDetails = new CellmlAnnotationViewMetadataViewDetailsWidget(pParent); mWebView = new QWebView(pParent); // A connection to handle the looking up of a resource and a resource id connect(mMetadataViewDetails->bioModelsDotNetView(), SIGNAL(qualifierLookupRequested(const QString &, const bool &)), this, SLOT(qualifierLookupRequested(const QString &, const bool &))); connect(mMetadataViewDetails->bioModelsDotNetView(), SIGNAL(resourceLookupRequested(const QString &, const bool &)), this, SLOT(resourceLookupRequested(const QString &, const bool &))); connect(mMetadataViewDetails->bioModelsDotNetView(), SIGNAL(resourceIdLookupRequested(const QString &, const QString &, const bool &)), this, SLOT(resourceIdLookupRequested(const QString &, const QString &, const bool &))); // Add our details widgets to our splitter addWidget(new Core::BorderedWidget(mCellmlElementDetails, false, true, true, false)); addWidget(new Core::BorderedWidget(mMetadataViewDetails, true, true, true, false)); addWidget(new Core::BorderedWidget(mWebView, true, true, false, false)); // Keep track of our splitter being moved connect(this, SIGNAL(splitterMoved(int,int)), this, SLOT(emitSplitterMoved())); // Retrieve the output template QFile qualifierInformationFile(":qualifierInformation"); qualifierInformationFile.open(QIODevice::ReadOnly); mQualifierInformationTemplate = QString(qualifierInformationFile.readAll()); qualifierInformationFile.close(); // Retrieve the SVG diagrams QFile modelQualifierFile(":modelQualifier"); QFile biologyQualifierFile(":biologyQualifier"); modelQualifierFile.open(QIODevice::ReadOnly); biologyQualifierFile.open(QIODevice::ReadOnly); mModelQualifierSvg = QString(modelQualifierFile.readAll()); mBiologyQualifierSvg = QString(biologyQualifierFile.readAll()); modelQualifierFile.close(); biologyQualifierFile.close(); } //============================================================================== CellmlAnnotationViewCellmlDetailsWidget::~CellmlAnnotationViewCellmlDetailsWidget() { // Delete the GUI delete mGui; } //============================================================================== void CellmlAnnotationViewCellmlDetailsWidget::retranslateUi() { // Retranslate our GUI // Note: we must also update the connection for our cmeta:id widget since it // gets recreated as a result of the retranslation... if (mCellmlElementDetails->cmetaIdValue()) disconnect(mCellmlElementDetails->cmetaIdValue(), SIGNAL(editTextChanged(const QString &)), this, SLOT(newCmetaId(const QString &))); mGui->retranslateUi(this); mCellmlElementDetails->retranslateUi(); mMetadataViewDetails->retranslateUi(); if (mCellmlElementDetails->cmetaIdValue()) connect(mCellmlElementDetails->cmetaIdValue(), SIGNAL(editTextChanged(const QString &)), this, SLOT(newCmetaId(const QString &))); } //============================================================================== void CellmlAnnotationViewCellmlDetailsWidget::updateGui(const CellmlAnnotationViewCellmlElementDetailsWidget::Items &pItems) { // Stop tracking changes to the cmeta:id value of our CellML element if (mCellmlElementDetails->cmetaIdValue()) disconnect(mCellmlElementDetails->cmetaIdValue(), SIGNAL(editTextChanged(const QString &)), this, SLOT(newCmetaId(const QString &))); // 'Clean up' our web view mWebView->setUrl(QString()); // Update our CellML element details GUI mCellmlElementDetails->updateGui(pItems); // Re-track changes to the cmeta:id value of our CellML element and update // our metadata details GUI if (mCellmlElementDetails->cmetaIdValue()) { connect(mCellmlElementDetails->cmetaIdValue(), SIGNAL(editTextChanged(const QString &)), this, SLOT(newCmetaId(const QString &))); newCmetaId(mCellmlElementDetails->cmetaIdValue()->currentText()); } } //============================================================================== void CellmlAnnotationViewCellmlDetailsWidget::updateSizes(const QList<int> &pSizes) { // The splitter of another CellmlAnnotationViewCellmlDetailsWidget object // has been moved, so update our sizes setSizes(pSizes); } //============================================================================== void CellmlAnnotationViewCellmlDetailsWidget::emitSplitterMoved() { // Let whoever know that our splitter has been moved emit splitterMoved(sizes()); } //============================================================================== void CellmlAnnotationViewCellmlDetailsWidget::newCmetaId(const QString &pCmetaId) { // Retrieve the RDF triples for the cmeta:id CellMLSupport::CellmlFileRdfTriples rdfTriples = pCmetaId.isEmpty()? CellMLSupport::CellmlFileRdfTriples(): mParent->cellmlFile()->rdfTriples(pCmetaId); // Check that we are not dealing with the same RDF triples // Note: this may happen when manually typing the name of a cmeta:id and the // QComboBox suggesting something for you, e.g. you start typing "C_" // and the QComboBox suggests "C_C" (which will get us here) and then // you finish typing "C_C" (which will also get us here) static CellMLSupport::CellmlFileRdfTriples oldRdfTriples = CellMLSupport::CellmlFileRdfTriples(mParent->cellmlFile()); if (rdfTriples == oldRdfTriples) return; oldRdfTriples = rdfTriples; // 'Clean up' our web view mWebView->setUrl(QString()); // Update its metadata details mMetadataViewDetails->updateGui(rdfTriples); } //============================================================================== void CellmlAnnotationViewCellmlDetailsWidget::qualifierLookupRequested(const QString &pQualifier, const bool &pRetranslate) { Q_UNUSED(pRetranslate); // The user requested a qualifier to be looked up, so generate a web page // containing some information about the qualifier // Note: ideally, there would be a way to refer to a particular qualifier // using http://biomodels.net/qualifiers/, but that would require // anchors and they don't have any, so instead we use the information // which can be found on that site and present it to the user in the // form of a web page... if (pQualifier.isEmpty()) return; // Generate the web page containing some information about the qualifier QString qualifierSvg; QString shortDescription; QString longDescription; if (!pQualifier.compare("model:is")) { qualifierSvg = mModelQualifierSvg; shortDescription = tr("Identity"); longDescription = tr("The modelling object represented by the model element is identical with the subject of the referenced resource (\"Modelling Object B\"). For instance, this qualifier might be used to link an encoded model to a database of models."); } else if (!pQualifier.compare("model:isDerivedFrom")) { qualifierSvg = mModelQualifierSvg; shortDescription = tr("Origin"); longDescription = tr("The modelling object represented by the model element is derived from the modelling object represented by the referenced resource (\"Modelling Object B\"). This relation may be used, for instance, to express a refinement or adaptation in usage for a previously described modelling component."); } else if (!pQualifier.compare("model:isDescribedBy")) { qualifierSvg = mModelQualifierSvg; shortDescription = tr("Description"); longDescription = tr("The modelling object represented by the model element is described by the subject of the referenced resource (\"Modelling Object B\"). This relation might be used to link a model or a kinetic law to the literature that describes it."); } else if (!pQualifier.compare("bio:encodes")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Encodement"); longDescription = tr("The biological entity represented by the model element encodes, directly or transitively, the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to express, for example, that a specific DNA sequence encodes a particular protein."); } else if (!pQualifier.compare("bio:hasPart")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Part"); longDescription = tr("The biological entity represented by the model element includes the subject of the referenced resource (\"Biological Entity B\"), either physically or logically. This relation might be used to link a complex to the description of its components."); } else if (!pQualifier.compare("bio:hasProperty")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Property"); longDescription = tr("The subject of the referenced resource (\"Biological Entity B\") is a property of the biological entity represented by the model element. This relation might be used when a biological entity exhibits a certain enzymatic activity or exerts a specific function."); } else if (!pQualifier.compare("bio:hasVersion")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Version"); longDescription = tr("The subject of the referenced resource (\"Biological Entity B\") is a version or an instance of the biological entity represented by the model element. This relation may be used to represent an isoform or modified form of a biological entity."); } else if (!pQualifier.compare("bio:is")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Indentity"); longDescription = tr("The biological entity represented by the model element has identity with the subject of the referenced resource (\"Biological Entity B\"). This relation might be used to link a reaction to its exact counterpart in a database, for instance."); } else if (!pQualifier.compare("bio:isDescribedBy")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Description"); longDescription = tr("The biological entity represented by the model element is described by the subject of the referenced resource (\"Biological Entity B\"). This relation should be used, for instance, to link a species or a parameter to the literature that describes the concentration of that species or the value of that parameter."); } else if (!pQualifier.compare("bio:isEncodedBy")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Encoder"); longDescription = tr("The biological entity represented by the model element is encoded, directly or transitively, by the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to express, for example, that a protein is encoded by a specific DNA sequence."); } else if (!pQualifier.compare("bio:isHomologTo")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Homolog"); longDescription = tr("The biological entity represented by the model element is homologous to the subject of the referenced resource (\"Biological Entity B\"). This relation can be used to represent biological entities that share a common ancestor."); } else if (!pQualifier.compare("bio:isPartOf")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Parthood"); longDescription = tr("The biological entity represented by the model element is a physical or logical part of the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to link a model component to a description of the complex in which it is a part."); } else if (!pQualifier.compare("bio:isPropertyOf")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Property bearer"); longDescription = tr("The biological entity represented by the model element is a property of the referenced resource (\"Biological Entity B\")."); } else if (!pQualifier.compare("bio:isVersionOf")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Hypernym"); longDescription = tr("The biological entity represented by the model element is a version or an instance of the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to represent, for example, the 'superclass' or 'parent' form of a particular biological entity."); } else if (!pQualifier.compare("bio:occursIn")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Container"); longDescription = tr("The biological entity represented by the model element is physically limited to a location, which is the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to ascribe a compartmental location, within which a reaction takes place."); } else if (!pQualifier.compare("bio:hasTaxon")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Taxon"); longDescription = tr("The biological entity represented by the model element is taxonomically restricted, where the restriction is the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to ascribe a species restriction to a biochemical reaction."); } else { qualifierSvg = ""; shortDescription = tr("Unknown"); longDescription = tr("Unknown"); } // Show the information mWebView->setHtml(mQualifierInformationTemplate.arg(pQualifier, qualifierSvg, shortDescription, longDescription, Core::copyright())); } //============================================================================== void CellmlAnnotationViewCellmlDetailsWidget::resourceLookupRequested(const QString &pResource, const bool &pRetranslate) { // The user requested a resource to be looked up, so retrieve it using // identifiers.org, but only if we are not retranslating since the looking // up would already be correct if (!pRetranslate) mWebView->setUrl("http://identifiers.org/"+pResource+"/?redirect=true"); //---GRY--- NOTE THAT redirect=true DOESN'T WORK AT THE MOMENT, SO WE DO // END UP WITH A FRAME, BUT THE identifiers.org GUYS ARE GOING // TO 'FIX' THAT, SO WE SHOULD BE READY FOR WHEN IT'S DONE... } //============================================================================== void CellmlAnnotationViewCellmlDetailsWidget::resourceIdLookupRequested(const QString &pResource, const QString &pId, const bool &pRetranslate) { // The user requested a resource id to be looked up, so retrieve it using // identifiers.org, but only if we are not retranslating since the looking // up would already be correct if (!pRetranslate) mWebView->setUrl("http://identifiers.org/"+pResource+"/"+pId+"?profile=most_reliable&redirect=true"); } //============================================================================== void CellmlAnnotationViewCellmlDetailsWidget::metadataUpdated() { // Some metadata has been updated, so we need to update the metadata // information we show to the user newCmetaId(mCellmlElementDetails->cmetaIdValue()->currentText()); } //============================================================================== } // namespace CellMLAnnotationView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Minor improvement to our handling of the removal of some/all the metadata of a CellML file (#78).<commit_after>//============================================================================== // CellML annotation view CellML details widget //============================================================================== #include "borderedwidget.h" #include "cellmlannotationviewcellmldetailswidget.h" #include "cellmlannotationviewmetadatabiomodelsdotnetviewdetailswidget.h" #include "cellmlannotationviewwidget.h" #include "cellmlannotationviewmetadataviewdetailswidget.h" #include "coreutils.h" //============================================================================== #include "ui_cellmlannotationviewcellmldetailswidget.h" //============================================================================== #include <QComboBox> #include <QFile> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> #include <QWebView> //============================================================================== #include <QJsonParser> //============================================================================== namespace OpenCOR { namespace CellMLAnnotationView { //============================================================================== CellmlAnnotationViewCellmlDetailsWidget::CellmlAnnotationViewCellmlDetailsWidget(CellmlAnnotationViewWidget *pParent) : QSplitter(pParent), CommonWidget(pParent), mParent(pParent), mGui(new Ui::CellmlAnnotationViewCellmlDetailsWidget) { // Set up the GUI mGui->setupUi(this); // Create our details widgets mCellmlElementDetails = new CellmlAnnotationViewCellmlElementDetailsWidget(pParent); mMetadataViewDetails = new CellmlAnnotationViewMetadataViewDetailsWidget(pParent); mWebView = new QWebView(pParent); // A connection to handle the looking up of a resource and a resource id connect(mMetadataViewDetails->bioModelsDotNetView(), SIGNAL(qualifierLookupRequested(const QString &, const bool &)), this, SLOT(qualifierLookupRequested(const QString &, const bool &))); connect(mMetadataViewDetails->bioModelsDotNetView(), SIGNAL(resourceLookupRequested(const QString &, const bool &)), this, SLOT(resourceLookupRequested(const QString &, const bool &))); connect(mMetadataViewDetails->bioModelsDotNetView(), SIGNAL(resourceIdLookupRequested(const QString &, const QString &, const bool &)), this, SLOT(resourceIdLookupRequested(const QString &, const QString &, const bool &))); // Add our details widgets to our splitter addWidget(new Core::BorderedWidget(mCellmlElementDetails, false, true, true, false)); addWidget(new Core::BorderedWidget(mMetadataViewDetails, true, true, true, false)); addWidget(new Core::BorderedWidget(mWebView, true, true, false, false)); // Keep track of our splitter being moved connect(this, SIGNAL(splitterMoved(int,int)), this, SLOT(emitSplitterMoved())); // Retrieve the output template QFile qualifierInformationFile(":qualifierInformation"); qualifierInformationFile.open(QIODevice::ReadOnly); mQualifierInformationTemplate = QString(qualifierInformationFile.readAll()); qualifierInformationFile.close(); // Retrieve the SVG diagrams QFile modelQualifierFile(":modelQualifier"); QFile biologyQualifierFile(":biologyQualifier"); modelQualifierFile.open(QIODevice::ReadOnly); biologyQualifierFile.open(QIODevice::ReadOnly); mModelQualifierSvg = QString(modelQualifierFile.readAll()); mBiologyQualifierSvg = QString(biologyQualifierFile.readAll()); modelQualifierFile.close(); biologyQualifierFile.close(); } //============================================================================== CellmlAnnotationViewCellmlDetailsWidget::~CellmlAnnotationViewCellmlDetailsWidget() { // Delete the GUI delete mGui; } //============================================================================== void CellmlAnnotationViewCellmlDetailsWidget::retranslateUi() { // Retranslate our GUI // Note: we must also update the connection for our cmeta:id widget since it // gets recreated as a result of the retranslation... if (mCellmlElementDetails->cmetaIdValue()) disconnect(mCellmlElementDetails->cmetaIdValue(), SIGNAL(editTextChanged(const QString &)), this, SLOT(newCmetaId(const QString &))); mGui->retranslateUi(this); mCellmlElementDetails->retranslateUi(); mMetadataViewDetails->retranslateUi(); if (mCellmlElementDetails->cmetaIdValue()) connect(mCellmlElementDetails->cmetaIdValue(), SIGNAL(editTextChanged(const QString &)), this, SLOT(newCmetaId(const QString &))); } //============================================================================== void CellmlAnnotationViewCellmlDetailsWidget::updateGui(const CellmlAnnotationViewCellmlElementDetailsWidget::Items &pItems) { // Stop tracking changes to the cmeta:id value of our CellML element if (mCellmlElementDetails->cmetaIdValue()) disconnect(mCellmlElementDetails->cmetaIdValue(), SIGNAL(editTextChanged(const QString &)), this, SLOT(newCmetaId(const QString &))); // 'Clean up' our web view mWebView->setUrl(QString()); // Update our CellML element details GUI mCellmlElementDetails->updateGui(pItems); // Re-track changes to the cmeta:id value of our CellML element and update // our metadata details GUI if (mCellmlElementDetails->cmetaIdValue()) { connect(mCellmlElementDetails->cmetaIdValue(), SIGNAL(editTextChanged(const QString &)), this, SLOT(newCmetaId(const QString &))); newCmetaId(mCellmlElementDetails->cmetaIdValue()->currentText()); } } //============================================================================== void CellmlAnnotationViewCellmlDetailsWidget::updateSizes(const QList<int> &pSizes) { // The splitter of another CellmlAnnotationViewCellmlDetailsWidget object // has been moved, so update our sizes setSizes(pSizes); } //============================================================================== void CellmlAnnotationViewCellmlDetailsWidget::emitSplitterMoved() { // Let whoever know that our splitter has been moved emit splitterMoved(sizes()); } //============================================================================== void CellmlAnnotationViewCellmlDetailsWidget::newCmetaId(const QString &pCmetaId) { // Retrieve the RDF triples for the cmeta:id CellMLSupport::CellmlFileRdfTriples rdfTriples = pCmetaId.isEmpty()? CellMLSupport::CellmlFileRdfTriples(): mParent->cellmlFile()->rdfTriples(pCmetaId); // Check that we are not dealing with the same RDF triples // Note: this may happen when manually typing the name of a cmeta:id and the // QComboBox suggesting something for you, e.g. you start typing "C_" // and the QComboBox suggests "C_C" (which will get us here) and then // you finish typing "C_C" (which will also get us here) static CellMLSupport::CellmlFileRdfTriples oldRdfTriples = CellMLSupport::CellmlFileRdfTriples(mParent->cellmlFile()); if (rdfTriples == oldRdfTriples) return; oldRdfTriples = rdfTriples; // 'Clean up' our web view mWebView->setUrl(QString()); // Update its metadata details mMetadataViewDetails->updateGui(rdfTriples); } //============================================================================== void CellmlAnnotationViewCellmlDetailsWidget::qualifierLookupRequested(const QString &pQualifier, const bool &pRetranslate) { Q_UNUSED(pRetranslate); // The user requested a qualifier to be looked up, so generate a web page // containing some information about the qualifier // Note: ideally, there would be a way to refer to a particular qualifier // using http://biomodels.net/qualifiers/, but that would require // anchors and they don't have any, so instead we use the information // which can be found on that site and present it to the user in the // form of a web page... if (pQualifier.isEmpty()) return; // Generate the web page containing some information about the qualifier QString qualifierSvg; QString shortDescription; QString longDescription; if (!pQualifier.compare("model:is")) { qualifierSvg = mModelQualifierSvg; shortDescription = tr("Identity"); longDescription = tr("The modelling object represented by the model element is identical with the subject of the referenced resource (\"Modelling Object B\"). For instance, this qualifier might be used to link an encoded model to a database of models."); } else if (!pQualifier.compare("model:isDerivedFrom")) { qualifierSvg = mModelQualifierSvg; shortDescription = tr("Origin"); longDescription = tr("The modelling object represented by the model element is derived from the modelling object represented by the referenced resource (\"Modelling Object B\"). This relation may be used, for instance, to express a refinement or adaptation in usage for a previously described modelling component."); } else if (!pQualifier.compare("model:isDescribedBy")) { qualifierSvg = mModelQualifierSvg; shortDescription = tr("Description"); longDescription = tr("The modelling object represented by the model element is described by the subject of the referenced resource (\"Modelling Object B\"). This relation might be used to link a model or a kinetic law to the literature that describes it."); } else if (!pQualifier.compare("bio:encodes")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Encodement"); longDescription = tr("The biological entity represented by the model element encodes, directly or transitively, the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to express, for example, that a specific DNA sequence encodes a particular protein."); } else if (!pQualifier.compare("bio:hasPart")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Part"); longDescription = tr("The biological entity represented by the model element includes the subject of the referenced resource (\"Biological Entity B\"), either physically or logically. This relation might be used to link a complex to the description of its components."); } else if (!pQualifier.compare("bio:hasProperty")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Property"); longDescription = tr("The subject of the referenced resource (\"Biological Entity B\") is a property of the biological entity represented by the model element. This relation might be used when a biological entity exhibits a certain enzymatic activity or exerts a specific function."); } else if (!pQualifier.compare("bio:hasVersion")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Version"); longDescription = tr("The subject of the referenced resource (\"Biological Entity B\") is a version or an instance of the biological entity represented by the model element. This relation may be used to represent an isoform or modified form of a biological entity."); } else if (!pQualifier.compare("bio:is")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Indentity"); longDescription = tr("The biological entity represented by the model element has identity with the subject of the referenced resource (\"Biological Entity B\"). This relation might be used to link a reaction to its exact counterpart in a database, for instance."); } else if (!pQualifier.compare("bio:isDescribedBy")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Description"); longDescription = tr("The biological entity represented by the model element is described by the subject of the referenced resource (\"Biological Entity B\"). This relation should be used, for instance, to link a species or a parameter to the literature that describes the concentration of that species or the value of that parameter."); } else if (!pQualifier.compare("bio:isEncodedBy")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Encoder"); longDescription = tr("The biological entity represented by the model element is encoded, directly or transitively, by the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to express, for example, that a protein is encoded by a specific DNA sequence."); } else if (!pQualifier.compare("bio:isHomologTo")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Homolog"); longDescription = tr("The biological entity represented by the model element is homologous to the subject of the referenced resource (\"Biological Entity B\"). This relation can be used to represent biological entities that share a common ancestor."); } else if (!pQualifier.compare("bio:isPartOf")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Parthood"); longDescription = tr("The biological entity represented by the model element is a physical or logical part of the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to link a model component to a description of the complex in which it is a part."); } else if (!pQualifier.compare("bio:isPropertyOf")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Property bearer"); longDescription = tr("The biological entity represented by the model element is a property of the referenced resource (\"Biological Entity B\")."); } else if (!pQualifier.compare("bio:isVersionOf")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Hypernym"); longDescription = tr("The biological entity represented by the model element is a version or an instance of the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to represent, for example, the 'superclass' or 'parent' form of a particular biological entity."); } else if (!pQualifier.compare("bio:occursIn")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Container"); longDescription = tr("The biological entity represented by the model element is physically limited to a location, which is the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to ascribe a compartmental location, within which a reaction takes place."); } else if (!pQualifier.compare("bio:hasTaxon")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Taxon"); longDescription = tr("The biological entity represented by the model element is taxonomically restricted, where the restriction is the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to ascribe a species restriction to a biochemical reaction."); } else { qualifierSvg = ""; shortDescription = tr("Unknown"); longDescription = tr("Unknown"); } // Show the information mWebView->setHtml(mQualifierInformationTemplate.arg(pQualifier, qualifierSvg, shortDescription, longDescription, Core::copyright())); } //============================================================================== void CellmlAnnotationViewCellmlDetailsWidget::resourceLookupRequested(const QString &pResource, const bool &pRetranslate) { // The user requested a resource to be looked up, so retrieve it using // identifiers.org, but only if we are not retranslating since the looking // up would already be correct if (!pRetranslate) mWebView->setUrl("http://identifiers.org/"+pResource+"/?redirect=true"); //---GRY--- NOTE THAT redirect=true DOESN'T WORK AT THE MOMENT, SO WE DO // END UP WITH A FRAME, BUT THE identifiers.org GUYS ARE GOING // TO 'FIX' THAT, SO WE SHOULD BE READY FOR WHEN IT'S DONE... } //============================================================================== void CellmlAnnotationViewCellmlDetailsWidget::resourceIdLookupRequested(const QString &pResource, const QString &pId, const bool &pRetranslate) { // The user requested a resource id to be looked up, so retrieve it using // identifiers.org, but only if we are not retranslating since the looking // up would already be correct if (!pRetranslate) mWebView->setUrl("http://identifiers.org/"+pResource+"/"+pId+"?profile=most_reliable&redirect=true"); } //============================================================================== void CellmlAnnotationViewCellmlDetailsWidget::metadataUpdated() { // Some metadata has been updated, so we need to update the metadata // information we show to the user if (mCellmlElementDetails->cmetaIdValue()) newCmetaId(mCellmlElementDetails->cmetaIdValue()->currentText()); } //============================================================================== } // namespace CellMLAnnotationView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "JsonInputFileFormatter.h" #include "MooseUtils.h" #include <vector> JsonInputFileFormatter::JsonInputFileFormatter() : _spaces(2), _level(0) {} std::string JsonInputFileFormatter::toString(const moosecontrib::Json::Value & root) { _stream.clear(); _stream.str(""); for (auto && name : root.getMemberNames()) addBlock(name, root[name], true); return _stream.str(); } void JsonInputFileFormatter::addLine(const std::string & line, size_t max_line_len, const std::string & comment) { if (line.empty() && comment.empty()) { _stream << "\n"; return; } std::string indent(_level * _spaces, ' '); auto doc = MooseUtils::trim(comment); if (doc.empty()) // Not comment so just print out the line normally { _stream << indent << line << "\n"; return; } // We have a comment so we need to break it up over multiple lines if necessary // and make sure that they all start at the same spot. _stream << indent << line; std::vector<std::string> elements; // if the line is empty we can just start the comment right away int extra = 1; if (line.empty()) extra = 0; // be careful of really long lines. int len = 100 - max_line_len - indent.size(); if (len < 0) len = 20; MooseUtils::tokenize(doc, elements, len, " \t"); std::string first(max_line_len - line.size() + extra, ' '); _stream << first << "# " << elements[0] << "\n"; std::string cindent(max_line_len + indent.size() + extra, ' '); for (size_t i = 1; i < elements.size(); ++i) _stream << cindent << "# " << elements[i] << "\n"; } void JsonInputFileFormatter::addBlock(const std::string & name, const moosecontrib::Json::Value & block, bool toplevel) { addLine(""); addLine("[./" + name + "]"); _level++; if (block.isMember("description") && !block["description"].asString().empty()) addLine("", 0, block["description"].asString()); if (block.isMember("parameters")) addParameters(block["parameters"]); if (block.isMember("actions")) { // there could be duplicate parameters across actions, last one wins moosecontrib::Json::Value all_params; auto & actions = block["actions"]; for (auto && name : actions.getMemberNames()) { auto & params = actions[name]["parameters"]; for (auto && param_name : params.getMemberNames()) all_params[param_name] = params[param_name]; } addParameters(all_params); } if (block.isMember("star")) addBlock("*", block["star"]); addTypes("subblock_types", block); addTypes("types", block); if (block.isMember("subblocks")) { auto & subblocks = block["subblocks"]; if (!subblocks.isNull()) for (auto && name : subblocks.getMemberNames()) addBlock(name, subblocks[name]); } _level--; if (toplevel) addLine("[]"); else addLine("[../]"); } void JsonInputFileFormatter::addTypes(const std::string & key, const moosecontrib::Json::Value & block) { if (!block.isMember(key)) return; auto & types = block[key]; if (types.isNull()) return; addLine(""); addLine("[./<types>]"); _level++; for (auto && name : types.getMemberNames()) addBlock("<" + name + ">", types[name]); _level--; addLine("[../]"); } void JsonInputFileFormatter::addParameters(const moosecontrib::Json::Value & params) { size_t max_name = 0; for (auto && name : params.getMemberNames()) if (name.size() > max_name) max_name = name.size(); size_t max_len = 0; std::map<std::string, std::string> lines; for (auto && name : params.getMemberNames()) { auto & param = params[name]; auto def = MooseUtils::trim(param["default"].asString()); if (def.find(' ') != std::string::npos) def = "'" + def + "'"; std::string indent(max_name - name.size(), ' '); std::string required; if (param["required"].asString() == "Yes") required = "(required)"; std::string l = name + indent + " = " + def + required; if (l.size() > max_len) max_len = l.size(); lines[name] = l; } for (auto && name : params.getMemberNames()) { auto & param = params[name]; auto & l = lines[name]; auto desc = param["description"].asString(); addLine(l, max_len, desc); auto group = param["group_name"].asString(); if (!group.empty()) addLine("", max_len + 1, "Group: " + group); // a +1 to account for an empty line } } <commit_msg>Fix top level block name in --dump<commit_after>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "JsonInputFileFormatter.h" #include "MooseUtils.h" #include <vector> JsonInputFileFormatter::JsonInputFileFormatter() : _spaces(2), _level(0) {} std::string JsonInputFileFormatter::toString(const moosecontrib::Json::Value & root) { _stream.clear(); _stream.str(""); for (auto && name : root.getMemberNames()) addBlock(name, root[name], true); return _stream.str(); } void JsonInputFileFormatter::addLine(const std::string & line, size_t max_line_len, const std::string & comment) { if (line.empty() && comment.empty()) { _stream << "\n"; return; } std::string indent(_level * _spaces, ' '); auto doc = MooseUtils::trim(comment); if (doc.empty()) // Not comment so just print out the line normally { _stream << indent << line << "\n"; return; } // We have a comment so we need to break it up over multiple lines if necessary // and make sure that they all start at the same spot. _stream << indent << line; std::vector<std::string> elements; // if the line is empty we can just start the comment right away int extra = 1; if (line.empty()) extra = 0; // be careful of really long lines. int len = 100 - max_line_len - indent.size(); if (len < 0) len = 20; MooseUtils::tokenize(doc, elements, len, " \t"); std::string first(max_line_len - line.size() + extra, ' '); _stream << first << "# " << elements[0] << "\n"; std::string cindent(max_line_len + indent.size() + extra, ' '); for (size_t i = 1; i < elements.size(); ++i) _stream << cindent << "# " << elements[i] << "\n"; } void JsonInputFileFormatter::addBlock(const std::string & name, const moosecontrib::Json::Value & block, bool toplevel) { addLine(""); if (toplevel) addLine("[" + name + "]"); else addLine("[./" + name + "]"); _level++; if (block.isMember("description") && !block["description"].asString().empty()) addLine("", 0, block["description"].asString()); if (block.isMember("parameters")) addParameters(block["parameters"]); if (block.isMember("actions")) { // there could be duplicate parameters across actions, last one wins moosecontrib::Json::Value all_params; auto & actions = block["actions"]; for (auto && name : actions.getMemberNames()) { auto & params = actions[name]["parameters"]; for (auto && param_name : params.getMemberNames()) all_params[param_name] = params[param_name]; } addParameters(all_params); } if (block.isMember("star")) addBlock("*", block["star"]); addTypes("subblock_types", block); addTypes("types", block); if (block.isMember("subblocks")) { auto & subblocks = block["subblocks"]; if (!subblocks.isNull()) for (auto && name : subblocks.getMemberNames()) addBlock(name, subblocks[name]); } _level--; if (toplevel) addLine("[]"); else addLine("[../]"); } void JsonInputFileFormatter::addTypes(const std::string & key, const moosecontrib::Json::Value & block) { if (!block.isMember(key)) return; auto & types = block[key]; if (types.isNull()) return; addLine(""); addLine("[./<types>]"); _level++; for (auto && name : types.getMemberNames()) addBlock("<" + name + ">", types[name]); _level--; addLine("[../]"); } void JsonInputFileFormatter::addParameters(const moosecontrib::Json::Value & params) { size_t max_name = 0; for (auto && name : params.getMemberNames()) if (name.size() > max_name) max_name = name.size(); size_t max_len = 0; std::map<std::string, std::string> lines; for (auto && name : params.getMemberNames()) { auto & param = params[name]; auto def = MooseUtils::trim(param["default"].asString()); if (def.find(' ') != std::string::npos) def = "'" + def + "'"; std::string indent(max_name - name.size(), ' '); std::string required; if (param["required"].asString() == "Yes") required = "(required)"; std::string l = name + indent + " = " + def + required; if (l.size() > max_len) max_len = l.size(); lines[name] = l; } for (auto && name : params.getMemberNames()) { auto & param = params[name]; auto & l = lines[name]; auto desc = param["description"].asString(); addLine(l, max_len, desc); auto group = param["group_name"].asString(); if (!group.empty()) addLine("", max_len + 1, "Group: " + group); // a +1 to account for an empty line } } <|endoftext|>
<commit_before> #include "pch.h" #include "PortTree.h" #include "Port.h" #include "Bridge.h" #include "stp.h" static const _bstr_t PortTreeString = "PortTree"; static const _bstr_t TreeIndexString = "TreeIndex"; static const _bstr_t PortPriorityString = "PortPriority"; HRESULT PortTree::Serialize (IXMLDOMDocument3* doc, IXMLDOMElementPtr& elementOut) const { IXMLDOMElementPtr portTreeElement; auto hr = doc->createElement (PortTreeString, &portTreeElement); assert(SUCCEEDED(hr)); portTreeElement->setAttribute (TreeIndexString, _variant_t(_treeIndex)); portTreeElement->setAttribute (PortPriorityString, _variant_t(GetPriority())); elementOut = portTreeElement; return S_OK; } HRESULT PortTree::Deserialize (IXMLDOMElement* portTreeElement) { _variant_t value; auto hr = portTreeElement->getAttribute (PortPriorityString, &value); if (FAILED(hr)) return hr; if (value.vt == VT_BSTR) SetPriority (wcstol (value.bstrVal, nullptr, 10)); return S_OK; } int PortTree::GetPriority() const { return STP_GetPortPriority (_parent->GetBridge()->GetStpBridge(), _parent->GetPortIndex(), _treeIndex); } void PortTree::SetPriority (int priority) { STP_SetPortPriority (_parent->GetBridge()->GetStpBridge(), _parent->GetPortIndex(), _treeIndex, (unsigned char) priority, GetMessageTime()); } static const NVP PortPrioNVPs[] = { { L"10 (16 dec)", 0x10 }, { L"20 (32 dec)", 0x20 }, { L"30 (48 dec)", 0x30 }, { L"40 (64 dec)", 0x40 }, { L"50 (80 dec)", 0x50 }, { L"60 (96 dec)", 0x60 }, { L"70 (112 dec)", 0x70 }, { L"80 (128 dec)", 0x80 }, { L"90 (144 dec)", 0x90 }, { L"A0 (160 dec)", 0xA0 }, { L"B0 (176 dec)", 0xB0 }, { L"C0 (192 dec)", 0xC0 }, { L"D0 (208 dec)", 0xD0 }, { L"E0 (224 dec)", 0xE0 }, { L"F0 (240 dec)", 0xF0 }, { nullptr, 0 }, }; const EnumProperty PortTree::Priority ( L"Bridge Priority", nullptr,//[](const std::vector<Object*>& objs) -> wstring static_cast<EnumProperty::Getter>(&GetPriority), static_cast<EnumProperty::Setter>(&SetPriority), PortPrioNVPs ); const PropertyOrGroup* const PortTree::Properties[] = { &Priority, }; <commit_msg>Bug fix.<commit_after> #include "pch.h" #include "PortTree.h" #include "Port.h" #include "Bridge.h" #include "stp.h" static const _bstr_t PortTreeString = "PortTree"; static const _bstr_t TreeIndexString = "TreeIndex"; static const _bstr_t PortPriorityString = "PortPriority"; HRESULT PortTree::Serialize (IXMLDOMDocument3* doc, IXMLDOMElementPtr& elementOut) const { IXMLDOMElementPtr portTreeElement; auto hr = doc->createElement (PortTreeString, &portTreeElement); assert(SUCCEEDED(hr)); portTreeElement->setAttribute (TreeIndexString, _variant_t(_treeIndex)); portTreeElement->setAttribute (PortPriorityString, _variant_t(GetPriority())); elementOut = portTreeElement; return S_OK; } HRESULT PortTree::Deserialize (IXMLDOMElement* portTreeElement) { _variant_t value; auto hr = portTreeElement->getAttribute (PortPriorityString, &value); if (FAILED(hr)) return hr; if (value.vt == VT_BSTR) SetPriority (wcstol (value.bstrVal, nullptr, 10)); return S_OK; } int PortTree::GetPriority() const { return STP_GetPortPriority (_parent->GetBridge()->GetStpBridge(), _parent->GetPortIndex(), _treeIndex); } void PortTree::SetPriority (int priority) { STP_SetPortPriority (_parent->GetBridge()->GetStpBridge(), _parent->GetPortIndex(), _treeIndex, (unsigned char) priority, GetMessageTime()); } static const NVP PortPrioNVPs[] = { { L"10 (16 dec)", 0x10 }, { L"20 (32 dec)", 0x20 }, { L"30 (48 dec)", 0x30 }, { L"40 (64 dec)", 0x40 }, { L"50 (80 dec)", 0x50 }, { L"60 (96 dec)", 0x60 }, { L"70 (112 dec)", 0x70 }, { L"80 (128 dec)", 0x80 }, { L"90 (144 dec)", 0x90 }, { L"A0 (160 dec)", 0xA0 }, { L"B0 (176 dec)", 0xB0 }, { L"C0 (192 dec)", 0xC0 }, { L"D0 (208 dec)", 0xD0 }, { L"E0 (224 dec)", 0xE0 }, { L"F0 (240 dec)", 0xF0 }, { nullptr, 0 }, }; const EnumProperty PortTree::Priority ( L"Bridge Priority", nullptr,//[](const std::vector<Object*>& objs) -> wstring static_cast<EnumProperty::Getter>(&GetPriority), static_cast<EnumProperty::Setter>(&SetPriority), PortPrioNVPs ); const PropertyOrGroup* const PortTree::Properties[] = { &Priority, nullptr }; <|endoftext|>
<commit_before>/** Definitions for the pqxx::result class and support classes. * * pqxx::result represents the set of result rows from a database query. * * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/result instead. * * Copyright (c) 2001-2017, Jeroen T. Vermeulen. * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. */ #ifndef PQXX_H_RESULT #define PQXX_H_RESULT #include "pqxx/compiler-public.hxx" #include "pqxx/compiler-internal-pre.hxx" #include <ios> #include <stdexcept> #include "pqxx/except" #include "pqxx/types" #include "pqxx/util" /* Methods tested in eg. self-test program test001 are marked with "//[t01]" */ // TODO: Support SQL arrays namespace pqxx { namespace internal { PQXX_LIBEXPORT void clear_result(const pq::PGresult *); namespace gate { class result_connection; class result_creation; class result_row; class result_sql_cursor; } // namespace internal::gate } // namespace internal /// Result set containing data returned by a query or command. /** This behaves as a container (as defined by the C++ standard library) and * provides random access const iterators to iterate over its rows. A row * can also be accessed by indexing a result R by the row's zero-based * number: * * @code * for (result::size_type i=0; i < R.size(); ++i) Process(R[i]); * @endcode * * Result sets in libpqxx are lightweight, reference-counted wrapper objects * which are relatively small and cheap to copy. Think of a result object as * a "smart pointer" to an underlying result set. * * @warning The result set that a result object points to is not thread-safe. * If you copy a result object, it still refers to the same underlying result * set. So never copy, destroy, query, or otherwise access a result while * another thread may be copying, destroying, querying, or otherwise accessing * the same result set--even if it is doing so through a different result * object! */ class PQXX_LIBEXPORT result { public: using size_type = result_size_type; using difference_type = result_difference_type; using reference = row; using const_iterator = const_result_iterator; using pointer = const_iterator; using iterator = const_iterator; using const_reverse_iterator = const_reverse_result_iterator; using reverse_iterator = const_reverse_iterator; result() noexcept : m_data(make_data_pointer()), m_query() {} //[t03] result(const result &rhs) noexcept : //[t01] m_data(rhs.m_data), m_query(rhs.m_query) {} result &operator=(const result &rhs) noexcept //[t10] { m_data = rhs.m_data; m_query = rhs.m_query; return *this; } /** * @name Comparisons */ //@{ bool operator==(const result &) const noexcept; //[t70] bool operator!=(const result &rhs) const noexcept //[t70] { return !operator==(rhs); } //@} const_reverse_iterator rbegin() const; //[t75] const_reverse_iterator crbegin() const; const_reverse_iterator rend() const; //[t75] const_reverse_iterator crend() const; const_iterator begin() const noexcept; //[t01] const_iterator cbegin() const noexcept; inline const_iterator end() const noexcept; //[t01] inline const_iterator cend() const noexcept; reference front() const noexcept; //[t74] reference back() const noexcept; //[t75] PQXX_PURE size_type size() const noexcept; //[t02] PQXX_PURE bool empty() const noexcept; //[t11] size_type capacity() const noexcept { return size(); } //[t20] void swap(result &) noexcept; //[t77] const row operator[](size_type i) const noexcept; //[t02] const row at(size_type) const; //[t10] void clear() noexcept { m_data.reset(); m_query.erase(); } //[t20] /** * @name Column information */ //@{ /// Number of columns in result. PQXX_PURE row_size_type columns() const noexcept; //[t11] /// Number of given column (throws exception if it doesn't exist). row_size_type column_number(const char ColName[]) const; //[t11] /// Number of given column (throws exception if it doesn't exist). row_size_type column_number(const std::string &Name) const //[t11] {return column_number(Name.c_str());} /// Name of column with this number (throws exception if it doesn't exist) const char *column_name(row_size_type Number) const; //[t11] /// Type of given column oid column_type(row_size_type ColNum) const; //[t07] /// Type of given column oid column_type(int ColNum) const //[t07] { return column_type(row_size_type(ColNum)); } /// Type of given column oid column_type(const std::string &ColName) const //[t07] { return column_type(column_number(ColName)); } /// Type of given column oid column_type(const char ColName[]) const //[t07] { return column_type(column_number(ColName)); } /// What table did this column come from? oid column_table(row_size_type ColNum) const; //[t02] /// What table did this column come from? oid column_table(int ColNum) const //[t02] { return column_table(row_size_type(ColNum)); } /// What table did this column come from? oid column_table(const std::string &ColName) const //[t02] { return column_table(column_number(ColName)); } /// What column in its table did this column come from? row_size_type table_column(row_size_type ColNum) const; //[t93] /// What column in its table did this column come from? row_size_type table_column(int ColNum) const //[t93] { return table_column(row_size_type(ColNum)); } /// What column in its table did this column come from? row_size_type table_column(const std::string &ColName) const //[t93] { return table_column(column_number(ColName)); } //@} /// Query that produced this result, if available (empty string otherwise) PQXX_PURE const std::string &query() const noexcept; //[t70] /// If command was @c INSERT of 1 row, return oid of inserted row /** @return Identifier of inserted row if exactly one row was inserted, or * oid_none otherwise. */ PQXX_PURE oid inserted_oid() const; //[t13] /// If command was @c INSERT, @c UPDATE, or @c DELETE: number of affected rows /** @return Number of affected rows if last command was @c INSERT, @c UPDATE, * or @c DELETE; zero for all other commands. */ PQXX_PURE size_type affected_rows() const; //[t07] private: using data_pointer = std::shared_ptr<const internal::pq::PGresult>; /// Underlying libpq result set. data_pointer m_data; /// Factory for data_pointer. static data_pointer make_data_pointer( const internal::pq::PGresult *res=nullptr) { return data_pointer(res, internal::clear_result); } /// Query string. std::string m_query; friend class pqxx::field; PQXX_PURE const char *GetValue(size_type Row, row_size_type Col) const; PQXX_PURE bool GetIsNull(size_type Row, row_size_type Col) const; PQXX_PURE field_size_type GetLength( size_type, row_size_type) const noexcept; friend class pqxx::internal::gate::result_creation; result(internal::pq::PGresult *rhs, const std::string &Query); PQXX_PRIVATE void CheckStatus() const; friend class pqxx::internal::gate::result_connection; friend class pqxx::internal::gate::result_row; bool operator!() const noexcept { return !m_data.get(); } operator bool() const noexcept { return m_data.get() != nullptr; } [[noreturn]] PQXX_PRIVATE void ThrowSQLError( const std::string &Err, const std::string &Query) const; PQXX_PRIVATE PQXX_PURE int errorposition() const noexcept; PQXX_PRIVATE std::string StatusError() const; friend class pqxx::internal::gate::result_sql_cursor; PQXX_PURE const char *CmdStatus() const noexcept; }; } // namespace pqxx // Now include some types which depend on result, but which the user will // expect to see defined after including this header. #include "pqxx/result_iterator.hxx" #include "pqxx/field.hxx" // Implementations depending on those other types which depend on result. namespace pqxx { /// Write a result field to any type of stream /** This can be convenient when writing a field to an output stream. More * importantly, it lets you write a field to e.g. a @c stringstream which you * can then use to read, format and convert the field in ways that to() does not * support. * * Example: parse a field into a variable of the nonstandard * "<tt>long long</tt>" type. * * @code * extern result R; * long long L; * stringstream S; * * // Write field's string into S * S << R[0][0]; * * // Parse contents of S into L * S >> L; * @endcode */ template<typename CHAR> inline std::basic_ostream<CHAR> &operator<<( std::basic_ostream<CHAR> &S, const pqxx::field &F) //[t46] { S.write(F.c_str(), std::streamsize(F.size())); return S; } /// Convert a field's string contents to another type. template<typename T> inline void from_string(const field &F, T &Obj) //[t46] { from_string(F.c_str(), Obj, F.size()); } /// Convert a field to a string. template<> std::string to_string(const field &Obj); //[t74] } // namespace pqxx #include "pqxx/compiler-internal-post.hxx" #endif <commit_msg>Add missing export.<commit_after>/** Definitions for the pqxx::result class and support classes. * * pqxx::result represents the set of result rows from a database query. * * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/result instead. * * Copyright (c) 2001-2017, Jeroen T. Vermeulen. * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. */ #ifndef PQXX_H_RESULT #define PQXX_H_RESULT #include "pqxx/compiler-public.hxx" #include "pqxx/compiler-internal-pre.hxx" #include <ios> #include <stdexcept> #include "pqxx/except" #include "pqxx/types" #include "pqxx/util" /* Methods tested in eg. self-test program test001 are marked with "//[t01]" */ // TODO: Support SQL arrays namespace pqxx { namespace internal { PQXX_LIBEXPORT void clear_result(const pq::PGresult *); namespace gate { class result_connection; class result_creation; class result_row; class result_sql_cursor; } // namespace internal::gate } // namespace internal /// Result set containing data returned by a query or command. /** This behaves as a container (as defined by the C++ standard library) and * provides random access const iterators to iterate over its rows. A row * can also be accessed by indexing a result R by the row's zero-based * number: * * @code * for (result::size_type i=0; i < R.size(); ++i) Process(R[i]); * @endcode * * Result sets in libpqxx are lightweight, reference-counted wrapper objects * which are relatively small and cheap to copy. Think of a result object as * a "smart pointer" to an underlying result set. * * @warning The result set that a result object points to is not thread-safe. * If you copy a result object, it still refers to the same underlying result * set. So never copy, destroy, query, or otherwise access a result while * another thread may be copying, destroying, querying, or otherwise accessing * the same result set--even if it is doing so through a different result * object! */ class PQXX_LIBEXPORT result { public: using size_type = result_size_type; using difference_type = result_difference_type; using reference = row; using const_iterator = const_result_iterator; using pointer = const_iterator; using iterator = const_iterator; using const_reverse_iterator = const_reverse_result_iterator; using reverse_iterator = const_reverse_iterator; result() noexcept : m_data(make_data_pointer()), m_query() {} //[t03] result(const result &rhs) noexcept : //[t01] m_data(rhs.m_data), m_query(rhs.m_query) {} result &operator=(const result &rhs) noexcept //[t10] { m_data = rhs.m_data; m_query = rhs.m_query; return *this; } /** * @name Comparisons */ //@{ bool operator==(const result &) const noexcept; //[t70] bool operator!=(const result &rhs) const noexcept //[t70] { return !operator==(rhs); } //@} const_reverse_iterator rbegin() const; //[t75] const_reverse_iterator crbegin() const; const_reverse_iterator rend() const; //[t75] const_reverse_iterator crend() const; const_iterator begin() const noexcept; //[t01] const_iterator cbegin() const noexcept; inline const_iterator end() const noexcept; //[t01] inline const_iterator cend() const noexcept; reference front() const noexcept; //[t74] reference back() const noexcept; //[t75] PQXX_PURE size_type size() const noexcept; //[t02] PQXX_PURE bool empty() const noexcept; //[t11] size_type capacity() const noexcept { return size(); } //[t20] void swap(result &) noexcept; //[t77] const row operator[](size_type i) const noexcept; //[t02] const row at(size_type) const; //[t10] void clear() noexcept { m_data.reset(); m_query.erase(); } //[t20] /** * @name Column information */ //@{ /// Number of columns in result. PQXX_PURE row_size_type columns() const noexcept; //[t11] /// Number of given column (throws exception if it doesn't exist). row_size_type column_number(const char ColName[]) const; //[t11] /// Number of given column (throws exception if it doesn't exist). row_size_type column_number(const std::string &Name) const //[t11] {return column_number(Name.c_str());} /// Name of column with this number (throws exception if it doesn't exist) const char *column_name(row_size_type Number) const; //[t11] /// Type of given column oid column_type(row_size_type ColNum) const; //[t07] /// Type of given column oid column_type(int ColNum) const //[t07] { return column_type(row_size_type(ColNum)); } /// Type of given column oid column_type(const std::string &ColName) const //[t07] { return column_type(column_number(ColName)); } /// Type of given column oid column_type(const char ColName[]) const //[t07] { return column_type(column_number(ColName)); } /// What table did this column come from? oid column_table(row_size_type ColNum) const; //[t02] /// What table did this column come from? oid column_table(int ColNum) const //[t02] { return column_table(row_size_type(ColNum)); } /// What table did this column come from? oid column_table(const std::string &ColName) const //[t02] { return column_table(column_number(ColName)); } /// What column in its table did this column come from? row_size_type table_column(row_size_type ColNum) const; //[t93] /// What column in its table did this column come from? row_size_type table_column(int ColNum) const //[t93] { return table_column(row_size_type(ColNum)); } /// What column in its table did this column come from? row_size_type table_column(const std::string &ColName) const //[t93] { return table_column(column_number(ColName)); } //@} /// Query that produced this result, if available (empty string otherwise) PQXX_PURE const std::string &query() const noexcept; //[t70] /// If command was @c INSERT of 1 row, return oid of inserted row /** @return Identifier of inserted row if exactly one row was inserted, or * oid_none otherwise. */ PQXX_PURE oid inserted_oid() const; //[t13] /// If command was @c INSERT, @c UPDATE, or @c DELETE: number of affected rows /** @return Number of affected rows if last command was @c INSERT, @c UPDATE, * or @c DELETE; zero for all other commands. */ PQXX_PURE size_type affected_rows() const; //[t07] private: using data_pointer = std::shared_ptr<const internal::pq::PGresult>; /// Underlying libpq result set. data_pointer m_data; /// Factory for data_pointer. static data_pointer make_data_pointer( const internal::pq::PGresult *res=nullptr) { return data_pointer(res, internal::clear_result); } /// Query string. std::string m_query; friend class pqxx::field; PQXX_PURE const char *GetValue(size_type Row, row_size_type Col) const; PQXX_PURE bool GetIsNull(size_type Row, row_size_type Col) const; PQXX_PURE field_size_type GetLength( size_type, row_size_type) const noexcept; friend class pqxx::internal::gate::result_creation; result(internal::pq::PGresult *rhs, const std::string &Query); PQXX_PRIVATE void CheckStatus() const; friend class pqxx::internal::gate::result_connection; friend class pqxx::internal::gate::result_row; bool operator!() const noexcept { return !m_data.get(); } operator bool() const noexcept { return m_data.get() != nullptr; } [[noreturn]] PQXX_PRIVATE void ThrowSQLError( const std::string &Err, const std::string &Query) const; PQXX_PRIVATE PQXX_PURE int errorposition() const noexcept; PQXX_PRIVATE std::string StatusError() const; friend class pqxx::internal::gate::result_sql_cursor; PQXX_PURE const char *CmdStatus() const noexcept; }; } // namespace pqxx // Now include some types which depend on result, but which the user will // expect to see defined after including this header. #include "pqxx/result_iterator.hxx" #include "pqxx/field.hxx" // Implementations depending on those other types which depend on result. namespace pqxx { /// Write a result field to any type of stream /** This can be convenient when writing a field to an output stream. More * importantly, it lets you write a field to e.g. a @c stringstream which you * can then use to read, format and convert the field in ways that to() does not * support. * * Example: parse a field into a variable of the nonstandard * "<tt>long long</tt>" type. * * @code * extern result R; * long long L; * stringstream S; * * // Write field's string into S * S << R[0][0]; * * // Parse contents of S into L * S >> L; * @endcode */ template<typename CHAR> inline std::basic_ostream<CHAR> &operator<<( std::basic_ostream<CHAR> &S, const pqxx::field &F) //[t46] { S.write(F.c_str(), std::streamsize(F.size())); return S; } /// Convert a field's string contents to another type. template<typename T> inline void from_string(const field &F, T &Obj) //[t46] { from_string(F.c_str(), Obj, F.size()); } /// Convert a field to a string. template<> PQXX_LIBEXPORT std::string to_string(const field &Obj); //[t74] } // namespace pqxx #include "pqxx/compiler-internal-post.hxx" #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SlsCacheCompactor.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 06:09:41 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "SlsCacheCompactor.hxx" #include "SlsBitmapCache.hxx" #include <svx/svdpage.hxx> #include <set> using namespace std; namespace sd { namespace slidesorter { namespace cache { /** Compare elements of the bitmap cache according to their last access time. */ class AccessTimeComparator { public: bool operator () ( const CacheBitmapContainer::value_type& e1, const CacheBitmapContainer::value_type& e2) { return e1.second.mnLastAccessTime < e2.second.mnLastAccessTime; } }; typedef set<CacheBitmapContainer::value_type, AccessTimeComparator> SortedCache; //===== NoCompaction ======================================================== void NoCompaction::operator() (BitmapCache& rCache, sal_Int32 nMaximalSize) { } //===== CompactionByRemoval ================================================== void CompactionByRemoval::operator() ( BitmapCache& rCache, sal_Int32 nMaximalSize) { if (rCache.GetSize() > nMaximalSize) { OSL_TRACE ("bitmap cache uses to much space: %d > %d", rCache.GetSize(), nMaximalSize); // Sort the entries in the cache by creating a new container. SortedCache aSortedCache; copy ( rCache.GetContainer().begin(), rCache.GetContainer().end(), inserter(aSortedCache, aSortedCache.end())); // Free one bitmap at a time until there is enough free space. The // number of bitmaps in the cache is used as a guard against // infinite loops when the maximal cache size is too small of the // bitmaps are too large. while (rCache.GetSize() > nMaximalSize && ! aSortedCache.empty()) { CacheBitmapContainer::value_type aEntry (*aSortedCache.begin()); if ( ! aEntry.second.mbIsPrecious) { // Free the bitmap and thus increase the available space. rCache.ReleaseBitmap (aEntry.first); OSL_TRACE (" there are now %d bytes occupied after releasing the bitmap for page %d", rCache.GetSize(), aEntry.first->GetPageNum()); } aSortedCache.erase (aSortedCache.begin()); } } } //===== CompactionByReduction =============================================== void CompactionByReduction::operator() ( BitmapCache& rCache, sal_Int32 nMaximalSize) { if (rCache.GetSize() > nMaximalSize) { OSL_TRACE ("bitmap cache uses to much space: %d > %d", rCache.GetSize(), nMaximalSize); // Sort the entries in the cache by creating a new container. SortedCache aSortedCache; copy ( rCache.GetContainer().begin(), rCache.GetContainer().end(), inserter(aSortedCache, aSortedCache.end())); // Free one bitmap at a time until there is enough free space. The // number of bitmaps in the cache is used as a guard against // infinite loops when the maximal cache size is too small or the // bitmaps are too large. while (rCache.GetSize() > nMaximalSize && ! aSortedCache.empty()) { CacheBitmapContainer::value_type aEntry (*aSortedCache.begin()); if ( ! aEntry.second.mbIsPrecious) { Size aSize (aEntry.second.maBitmap.GetSizePixel()); if (aSize.Width() != 0) { int nWidth = 100; int nHeight = aSize.Height() * nWidth / aSize.Width() ; aEntry.second.maBitmap.Scale (Size(nWidth,nHeight)); rCache.SetBitmap ( aEntry.first, aEntry.second.maBitmap, false); } OSL_TRACE (" there are now %d bytes occupied after scaling down bitmap for page %d", rCache.GetSize(), aEntry.first->GetPageNum()); } aSortedCache.erase (aSortedCache.begin()); } } } } } } // end of namespace ::sd::slidesorter::cache <commit_msg>INTEGRATION: CWS impress69 (1.2.434); FILE MERGED 2005/10/14 11:01:20 af 1.2.434.3: RESYNC: (1.2-1.3); FILE MERGED 2005/09/21 15:54:45 af 1.2.434.2: #i54916# Support for bitmap compression. 2005/09/14 11:12:18 af 1.2.434.1: #i54589# Adaption to changes of the BitmapCache class.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SlsCacheCompactor.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-10-24 07:39:54 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "SlsCacheCompactor.hxx" #include "SlsBitmapCompressor.hxx" #include "SlsBitmapCache.hxx" #include "SlsCacheCompactor.hxx" #include "SlsCacheConfiguration.hxx" #include <rtl/ustring.hxx> #include <com/sun/star/uno/Any.hxx> #include <set> using namespace ::com::sun::star::uno; // Uncomment the definition of VERBOSE to get some more OSL_TRACE messages. #ifdef DEBUG //#define VERBOSE #endif namespace { /** This is a trivial implementation of the CacheCompactor interface class. It ignores calls to RequestCompaction() and thus will never decrease the total size of off-screen preview bitmaps. */ class NoCacheCompaction : public ::sd::slidesorter::cache::CacheCompactor { public: NoCacheCompaction ( ::sd::slidesorter::cache::BitmapCache& rCache, sal_Int32 nMaximalCacheSize) : CacheCompactor(rCache, nMaximalCacheSize) {} virtual void RequestCompaction (void) { /* Ignored */ }; protected: virtual void Run (void) { /* Do nothing */ }; }; /** This implementation of the CacheCompactor interface class uses one of several bitmap compression algorithms to reduce the number of the bytes of the off-screen previews in the bitmap cache. See the documentation of CacheCompactor::Create() for more details on configuration properties that control the choice of compression algorithm. */ class CacheCompactionByCompression : public ::sd::slidesorter::cache::CacheCompactor { public: CacheCompactionByCompression ( ::sd::slidesorter::cache::BitmapCache& rCache, sal_Int32 nMaximalCacheSize, const ::boost::shared_ptr< ::sd::slidesorter::cache::BitmapCompressor>& rpCompressor); protected: virtual void Run (void); private: ::boost::shared_ptr< ::sd::slidesorter::cache::BitmapCompressor> mpCompressor; }; } // end of anonymous namespace namespace sd { namespace slidesorter { namespace cache { ::std::auto_ptr<CacheCompactor> CacheCompactor::Create ( BitmapCache& rCache, sal_Int32 nMaximalCacheSize) { static const ::rtl::OUString sNone (RTL_CONSTASCII_USTRINGPARAM("None")); static const ::rtl::OUString sCompress (RTL_CONSTASCII_USTRINGPARAM("Compress")); static const ::rtl::OUString sErase (RTL_CONSTASCII_USTRINGPARAM("Erase")); static const ::rtl::OUString sResolution (RTL_CONSTASCII_USTRINGPARAM("ResolutionReduction")); static const ::rtl::OUString sPNGCompression (RTL_CONSTASCII_USTRINGPARAM("PNGCompression")); ::boost::shared_ptr<BitmapCompressor> pCompressor; ::rtl::OUString sCompressionPolicy(sPNGCompression); Any aCompressionPolicy (CacheConfiguration::Instance()->GetValue( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("CompressionPolicy")))); if (aCompressionPolicy.has<rtl::OUString>()) aCompressionPolicy >>= sCompressionPolicy; if (sCompressionPolicy == sNone) pCompressor.reset(new NoBitmapCompression()); else if (sCompressionPolicy == sErase) pCompressor.reset(new CompressionByDeletion()); else if (sCompressionPolicy == sResolution) pCompressor.reset(new ResolutionReduction()); else pCompressor.reset(new PngCompression()); ::std::auto_ptr<CacheCompactor> pCompactor (NULL); ::rtl::OUString sCompactionPolicy(sCompress); Any aCompactionPolicy (CacheConfiguration::Instance()->GetValue( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("CompactionPolicy")))); if (aCompactionPolicy.has<rtl::OUString>()) aCompactionPolicy >>= sCompactionPolicy; if (sCompactionPolicy == sNone) pCompactor.reset(new NoCacheCompaction(rCache,nMaximalCacheSize)); else pCompactor.reset(new CacheCompactionByCompression(rCache,nMaximalCacheSize,pCompressor)); return pCompactor; } void CacheCompactor::RequestCompaction (void) { if ( ! mbIsCompactionRunning && ! maCompactionTimer.IsActive()) maCompactionTimer.Start(); } CacheCompactor::CacheCompactor( BitmapCache& rCache, sal_Int32 nMaximalCacheSize) : mrCache(rCache), mnMaximalCacheSize(nMaximalCacheSize), mbIsCompactionRunning(false) { maCompactionTimer.SetTimeout(100 /*ms*/); maCompactionTimer.SetTimeoutHdl(LINK(this,CacheCompactor,CompactionCallback)); } IMPL_LINK(CacheCompactor, CompactionCallback, Timer*, pTimer) { mbIsCompactionRunning = true; try { Run(); } catch(::com::sun::star::uno::RuntimeException e) { } catch(::com::sun::star::uno::Exception e) { } mbIsCompactionRunning = false; return 1; } } } } // end of namespace ::sd::slidesorter::cache namespace { //===== CacheCompactionByCompression ========================================== CacheCompactionByCompression::CacheCompactionByCompression ( ::sd::slidesorter::cache::BitmapCache& rCache, sal_Int32 nMaximalCacheSize, const ::boost::shared_ptr< ::sd::slidesorter::cache::BitmapCompressor>& rpCompressor) : CacheCompactor(rCache,nMaximalCacheSize), mpCompressor(rpCompressor) { } void CacheCompactionByCompression::Run (void) { if (mrCache.GetSize() > mnMaximalCacheSize) { #ifdef VERBOSE OSL_TRACE ("bitmap cache uses to much space: %d > %d", mrCache.GetSize(), mnMaximalCacheSize); #endif ::std::auto_ptr< ::sd::slidesorter::cache::BitmapCache::CacheIndex> pIndex ( mrCache.GetCacheIndex(false,false)); ::sd::slidesorter::cache::BitmapCache::CacheIndex::iterator iIndex; for (iIndex=pIndex->begin(); iIndex!=pIndex->end(); ++iIndex) { if (*iIndex == NULL) continue; mrCache.Compress(*iIndex, mpCompressor); if (mrCache.GetSize() < mnMaximalCacheSize) break; } mrCache.ReCalculateTotalCacheSize(); #ifdef VERBOSE OSL_TRACE (" there are now %d bytes occupied", mrCache.GetSize()); #endif } } } // end of anonymous namespace <|endoftext|>
<commit_before>#pragma once #include <cstring> #include <pmmintrin.h> namespace rack { /** Abstraction of byte-aligned values for SIMD CPU acceleration. */ namespace simd { /** Generic class for vector types. This class is designed to be used just like you use scalars, with extra features for handling bitwise logic, conditions, loading, and storing. Usage example: float a[4], b[4]; float_4 a = float_4::load(in); float_4 b = 2.f * a / (1 - a); b *= sin(2 * M_PI * a); b.store(out); */ template <typename T, int N> struct Vector; /** Wrapper for `__m128` representing an aligned vector of 4 single-precision float values. */ template <> struct Vector<float, 4> { union { __m128 v; /** Accessing this array of scalars is slow and defeats the purpose of vectorizing. */ float s[4]; }; /** Constructs an uninitialized vector. */ Vector() {} /** Constructs a vector from a native `__m128` type. */ Vector(__m128 v) : v(v) {} /** Constructs a vector with all elements set to `x`. */ Vector(float x) { v = _mm_set1_ps(x); } /** Constructs a vector from four values. */ Vector(float x1, float x2, float x3, float x4) { v = _mm_set_ps(x1, x2, x3, x4); } /** Returns a vector initialized to zero. */ static Vector zero() { return Vector(_mm_setzero_ps()); } /** Returns a vector with all 1 bits. */ static Vector mask() { return _mm_castsi128_ps(_mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128())); } /** Reads an array of 4 values. */ static Vector load(const float *x) { /* My benchmarks show that _mm_loadu_ps() performs equally as fast as _mm_load_ps() when data is actually aligned. This post seems to agree. https://stackoverflow.com/a/20265193/272642 So use _mm_loadu_ps() for generality, so you can load unaligned arrays using the same function (although it will be slower). */ return Vector(_mm_loadu_ps(x)); } /** Writes an array of 4 values. */ void store(float *x) { _mm_storeu_ps(x, v); } // Conversions Vector(Vector<int32_t, 4> a); // Casts static Vector cast(Vector<int32_t, 4> a); }; template <> struct Vector<int32_t, 4> { union { __m128i v; int32_t s[4]; }; Vector() {} Vector(__m128i v) : v(v) {} Vector(int32_t x) { v = _mm_set1_epi32(x); } Vector(int32_t x1, int32_t x2, int32_t x3, int32_t x4) { v = _mm_set_epi32(x1, x2, x3, x4); } static Vector zero() { return Vector(_mm_setzero_si128()); } static Vector mask() { return Vector(_mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128())); } static Vector load(const int32_t *x) { // HACK // Use _mm_loadu_si128() because GCC doesn't support _mm_loadu_si32() return Vector(_mm_loadu_si128((__m128i*) x)); } void store(int32_t *x) { // HACK // Use _mm_storeu_si128() because GCC doesn't support _mm_storeu_si32() _mm_storeu_si128((__m128i*) x, v); } Vector(Vector<float, 4> a); static Vector cast(Vector<float, 4> a); }; // Conversions and casts inline Vector<float, 4>::Vector(Vector<int32_t, 4> a) { v = _mm_cvtepi32_ps(a.v); } inline Vector<int32_t, 4>::Vector(Vector<float, 4> a) { v = _mm_cvtps_epi32(a.v); } inline Vector<float, 4> Vector<float, 4>::cast(Vector<int32_t, 4> a) { return Vector(_mm_castsi128_ps(a.v)); } inline Vector<int32_t, 4> Vector<int32_t, 4>::cast(Vector<float, 4> a) { return Vector(_mm_castps_si128(a.v)); } // Instructions not available as operators /** `~a & b` */ inline Vector<float, 4> andnot(const Vector<float, 4> &a, const Vector<float, 4> &b) { return Vector<float, 4>(_mm_andnot_ps(a.v, b.v)); } // Operator overloads /** `a @ b` */ #define DECLARE_VECTOR_OPERATOR_INFIX(t, s, operator, func) \ inline Vector<t, s> operator(const Vector<t, s> &a, const Vector<t, s> &b) { \ return Vector<t, s>(func(a.v, b.v)); \ } /** `a @= b` */ #define DECLARE_VECTOR_OPERATOR_INCREMENT(t, s, operator, opfunc) \ inline Vector<t, s> &operator(Vector<t, s> &a, const Vector<t, s> &b) { \ a = opfunc(a, b); \ return a; \ } DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator+, _mm_add_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator+, _mm_add_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator-, _mm_sub_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator-, _mm_sub_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator*, _mm_mul_ps) // DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator*, NOT AVAILABLE IN SSE3) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator/, _mm_div_ps) // DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator/, NOT AVAILABLE IN SSE3) /* Use these to apply logic, bit masks, and conditions to elements. Boolean operators on vectors give 0x00000000 for false and 0xffffffff for true, for each vector element. Examples: Subtract 1 from value if greater than or equal to 1. x -= (x >= 1.f) & 1.f; */ DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator^, _mm_xor_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator^, _mm_xor_si128) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator&, _mm_and_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator&, _mm_and_si128) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator|, _mm_or_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator|, _mm_or_si128) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator+=, operator+) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator+=, operator+) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator-=, operator-) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator-=, operator-) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator*=, operator*) // DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator*=, NOT AVAILABLE IN SSE3) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator/=, operator/) // DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator/=, NOT AVAILABLE IN SSE3) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator^=, operator^) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator^=, operator^) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator&=, operator&) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator&=, operator&) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator|=, operator|) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator|=, operator|) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator==, _mm_cmpeq_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator==, _mm_cmpeq_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator>=, _mm_cmpge_ps) inline Vector<int32_t, 4> operator>=(const Vector<int32_t, 4> &a, const Vector<int32_t, 4> &b) { return Vector<int32_t, 4>(_mm_cmpgt_epi32(a.v, b.v)) ^ Vector<int32_t, 4>::mask(); } DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator>, _mm_cmpgt_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator>, _mm_cmpgt_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator<=, _mm_cmple_ps) inline Vector<int32_t, 4> operator<=(const Vector<int32_t, 4> &a, const Vector<int32_t, 4> &b) { return Vector<int32_t, 4>(_mm_cmplt_epi32(a.v, b.v)) ^ Vector<int32_t, 4>::mask(); } DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator<, _mm_cmplt_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator<, _mm_cmplt_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator!=, _mm_cmpneq_ps) inline Vector<int32_t, 4> operator!=(const Vector<int32_t, 4> &a, const Vector<int32_t, 4> &b) { return Vector<int32_t, 4>(_mm_cmpeq_epi32(a.v, b.v)) ^ Vector<int32_t, 4>::mask(); } /** `+a` */ inline Vector<float, 4> operator+(const Vector<float, 4> &a) { return a; } inline Vector<int32_t, 4> operator+(const Vector<int32_t, 4> &a) { return a; } /** `-a` */ inline Vector<float, 4> operator-(const Vector<float, 4> &a) { return 0.f - a; } inline Vector<int32_t, 4> operator-(const Vector<int32_t, 4> &a) { return 0 - a; } /** `++a` */ inline Vector<float, 4> &operator++(Vector<float, 4> &a) { a += 1.f; return a; } inline Vector<int32_t, 4> &operator++(Vector<int32_t, 4> &a) { a += 1; return a; } /** `--a` */ inline Vector<float, 4> &operator--(Vector<float, 4> &a) { a -= 1.f; return a; } inline Vector<int32_t, 4> &operator--(Vector<int32_t, 4> &a) { a -= 1; return a; } /** `a++` */ inline Vector<float, 4> operator++(Vector<float, 4> &a, int) { Vector<float, 4> b = a; ++a; return b; } inline Vector<int32_t, 4> operator++(Vector<int32_t, 4> &a, int) { Vector<int32_t, 4> b = a; ++a; return b; } /** `a--` */ inline Vector<float, 4> operator--(Vector<float, 4> &a, int) { Vector<float, 4> b = a; --a; return b; } inline Vector<int32_t, 4> operator--(Vector<int32_t, 4> &a, int) { Vector<int32_t, 4> b = a; --a; return b; } /** `~a` */ inline Vector<float, 4> operator~(const Vector<float, 4> &a) { return a ^ Vector<float, 4>::mask(); } inline Vector<int32_t, 4> operator~(const Vector<int32_t, 4> &a) { return a ^ Vector<int32_t, 4>::mask(); } // Typedefs typedef Vector<float, 4> float_4; typedef Vector<int32_t, 4> int32_4; } // namespace simd } // namespace rack <commit_msg>Add left/rightByteShift to simd<commit_after>#pragma once #include <cstring> #include <pmmintrin.h> namespace rack { /** Abstraction of byte-aligned values for SIMD CPU acceleration. */ namespace simd { /** Generic class for vector types. This class is designed to be used just like you use scalars, with extra features for handling bitwise logic, conditions, loading, and storing. Usage example: float a[4], b[4]; float_4 a = float_4::load(in); float_4 b = 2.f * a / (1 - a); b *= sin(2 * M_PI * a); b.store(out); */ template <typename T, int N> struct Vector; /** Wrapper for `__m128` representing an aligned vector of 4 single-precision float values. */ template <> struct Vector<float, 4> { union { __m128 v; /** Accessing this array of scalars is slow and defeats the purpose of vectorizing. */ float s[4]; }; /** Constructs an uninitialized vector. */ Vector() {} /** Constructs a vector from a native `__m128` type. */ Vector(__m128 v) : v(v) {} /** Constructs a vector with all elements set to `x`. */ Vector(float x) { v = _mm_set1_ps(x); } /** Constructs a vector from four values. */ Vector(float x1, float x2, float x3, float x4) { v = _mm_set_ps(x1, x2, x3, x4); } /** Returns a vector initialized to zero. */ static Vector zero() { return Vector(_mm_setzero_ps()); } /** Returns a vector with all 1 bits. */ static Vector mask() { return _mm_castsi128_ps(_mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128())); } /** Reads an array of 4 values. */ static Vector load(const float *x) { /* My benchmarks show that _mm_loadu_ps() performs equally as fast as _mm_load_ps() when data is actually aligned. This post seems to agree. https://stackoverflow.com/a/20265193/272642 So use _mm_loadu_ps() for generality, so you can load unaligned arrays using the same function (although it will be slower). */ return Vector(_mm_loadu_ps(x)); } /** Writes an array of 4 values. */ void store(float *x) { _mm_storeu_ps(x, v); } // Conversions Vector(Vector<int32_t, 4> a); // Casts static Vector cast(Vector<int32_t, 4> a); }; template <> struct Vector<int32_t, 4> { union { __m128i v; int32_t s[4]; }; Vector() {} Vector(__m128i v) : v(v) {} Vector(int32_t x) { v = _mm_set1_epi32(x); } Vector(int32_t x1, int32_t x2, int32_t x3, int32_t x4) { v = _mm_set_epi32(x1, x2, x3, x4); } static Vector zero() { return Vector(_mm_setzero_si128()); } static Vector mask() { return Vector(_mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128())); } static Vector load(const int32_t *x) { // HACK // Use _mm_loadu_si128() because GCC doesn't support _mm_loadu_si32() return Vector(_mm_loadu_si128((__m128i*) x)); } void store(int32_t *x) { // HACK // Use _mm_storeu_si128() because GCC doesn't support _mm_storeu_si32() _mm_storeu_si128((__m128i*) x, v); } Vector(Vector<float, 4> a); static Vector cast(Vector<float, 4> a); }; // Conversions and casts inline Vector<float, 4>::Vector(Vector<int32_t, 4> a) { v = _mm_cvtepi32_ps(a.v); } inline Vector<int32_t, 4>::Vector(Vector<float, 4> a) { v = _mm_cvtps_epi32(a.v); } inline Vector<float, 4> Vector<float, 4>::cast(Vector<int32_t, 4> a) { return Vector(_mm_castsi128_ps(a.v)); } inline Vector<int32_t, 4> Vector<int32_t, 4>::cast(Vector<float, 4> a) { return Vector(_mm_castps_si128(a.v)); } // Instructions not available as operators /** `~a & b` */ inline Vector<float, 4> andnot(const Vector<float, 4> &a, const Vector<float, 4> &b) { return Vector<float, 4>(_mm_andnot_ps(a.v, b.v)); } /** Shifts the entire vector (not the elements) to the left by `n` bytes (not bits) */ inline Vector<int32_t, 4> leftByteShift(const Vector<int32_t, 4> &a, int n) { return Vector<int32_t, 4>(_mm_slli_si128(a.v, n)); } inline Vector<int32_t, 4> rightByteShift(const Vector<int32_t, 4> &a, int n) { return Vector<int32_t, 4>(_mm_srli_si128(a.v, n)); } // Operator overloads /** `a @ b` */ #define DECLARE_VECTOR_OPERATOR_INFIX(t, s, operator, func) \ inline Vector<t, s> operator(const Vector<t, s> &a, const Vector<t, s> &b) { \ return Vector<t, s>(func(a.v, b.v)); \ } /** `a @= b` */ #define DECLARE_VECTOR_OPERATOR_INCREMENT(t, s, operator, opfunc) \ inline Vector<t, s> &operator(Vector<t, s> &a, const Vector<t, s> &b) { \ a = opfunc(a, b); \ return a; \ } DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator+, _mm_add_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator+, _mm_add_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator-, _mm_sub_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator-, _mm_sub_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator*, _mm_mul_ps) // DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator*, NOT AVAILABLE IN SSE3) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator/, _mm_div_ps) // DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator/, NOT AVAILABLE IN SSE3) /* Use these to apply logic, bit masks, and conditions to elements. Boolean operators on vectors give 0x00000000 for false and 0xffffffff for true, for each vector element. Examples: Subtract 1 from value if greater than or equal to 1. x -= (x >= 1.f) & 1.f; */ DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator^, _mm_xor_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator^, _mm_xor_si128) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator&, _mm_and_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator&, _mm_and_si128) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator|, _mm_or_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator|, _mm_or_si128) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator+=, operator+) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator+=, operator+) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator-=, operator-) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator-=, operator-) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator*=, operator*) // DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator*=, NOT AVAILABLE IN SSE3) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator/=, operator/) // DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator/=, NOT AVAILABLE IN SSE3) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator^=, operator^) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator^=, operator^) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator&=, operator&) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator&=, operator&) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator|=, operator|) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator|=, operator|) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator==, _mm_cmpeq_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator==, _mm_cmpeq_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator>=, _mm_cmpge_ps) inline Vector<int32_t, 4> operator>=(const Vector<int32_t, 4> &a, const Vector<int32_t, 4> &b) { return Vector<int32_t, 4>(_mm_cmpgt_epi32(a.v, b.v)) ^ Vector<int32_t, 4>::mask(); } DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator>, _mm_cmpgt_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator>, _mm_cmpgt_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator<=, _mm_cmple_ps) inline Vector<int32_t, 4> operator<=(const Vector<int32_t, 4> &a, const Vector<int32_t, 4> &b) { return Vector<int32_t, 4>(_mm_cmplt_epi32(a.v, b.v)) ^ Vector<int32_t, 4>::mask(); } DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator<, _mm_cmplt_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator<, _mm_cmplt_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator!=, _mm_cmpneq_ps) inline Vector<int32_t, 4> operator!=(const Vector<int32_t, 4> &a, const Vector<int32_t, 4> &b) { return Vector<int32_t, 4>(_mm_cmpeq_epi32(a.v, b.v)) ^ Vector<int32_t, 4>::mask(); } /** `+a` */ inline Vector<float, 4> operator+(const Vector<float, 4> &a) { return a; } inline Vector<int32_t, 4> operator+(const Vector<int32_t, 4> &a) { return a; } /** `-a` */ inline Vector<float, 4> operator-(const Vector<float, 4> &a) { return 0.f - a; } inline Vector<int32_t, 4> operator-(const Vector<int32_t, 4> &a) { return 0 - a; } /** `++a` */ inline Vector<float, 4> &operator++(Vector<float, 4> &a) { a += 1.f; return a; } inline Vector<int32_t, 4> &operator++(Vector<int32_t, 4> &a) { a += 1; return a; } /** `--a` */ inline Vector<float, 4> &operator--(Vector<float, 4> &a) { a -= 1.f; return a; } inline Vector<int32_t, 4> &operator--(Vector<int32_t, 4> &a) { a -= 1; return a; } /** `a++` */ inline Vector<float, 4> operator++(Vector<float, 4> &a, int) { Vector<float, 4> b = a; ++a; return b; } inline Vector<int32_t, 4> operator++(Vector<int32_t, 4> &a, int) { Vector<int32_t, 4> b = a; ++a; return b; } /** `a--` */ inline Vector<float, 4> operator--(Vector<float, 4> &a, int) { Vector<float, 4> b = a; --a; return b; } inline Vector<int32_t, 4> operator--(Vector<int32_t, 4> &a, int) { Vector<int32_t, 4> b = a; --a; return b; } /** `~a` */ inline Vector<float, 4> operator~(const Vector<float, 4> &a) { return a ^ Vector<float, 4>::mask(); } inline Vector<int32_t, 4> operator~(const Vector<int32_t, 4> &a) { return a ^ Vector<int32_t, 4>::mask(); } // Typedefs typedef Vector<float, 4> float_4; typedef Vector<int32_t, 4> int32_4; } // namespace simd } // namespace rack <|endoftext|>
<commit_before>#include "Application.h" #include <iostream> #include "Display.h" #include "Util/Random.h" #include "States/Playing_State.h" #include "States/Splash_Screen.h" #include "Game/Equipment/Equipment_Data.h" namespace { void calculateFPS() { static sf::Clock timer; static sf::Clock printTimer; static auto numFrames = 0; numFrames++; if (printTimer.getElapsedTime().asSeconds() >= 1.0f) { auto fps = (float)numFrames / timer.getElapsedTime().asSeconds(); printTimer.restart(); std::cout << fps << std::endl; numFrames = 0; timer.restart(); } } } Application::Application() { Display ::init ("Hero - V0.1"); Random ::init (); Equipment ::initData (m_resourceHolder); //pushState(std::make_unique<State::Splash_Screen>(*this)); pushState(std::make_unique<State::Playing>(*this)); } void Application::runMainLoop() { sf::Clock c; while (Display::isOpen()) { auto dt = c.restart().asSeconds(); Display::clear({50, 50, 100}); m_states.top()->input (); m_states.top()->update (dt); m_states.top()->draw (); Display::update (); calculateFPS (); Display::pollEvents(*m_states.top()); } } const Resource_Holder& Application::getResources() const { return m_resourceHolder; } void Application::pushState(std::unique_ptr<State::State_Base> state) { m_states.push(std::move(state)); } void Application::popState() { m_states.pop(); } <commit_msg>Fix a dumb indent<commit_after>#include "Application.h" #include <iostream> #include "Display.h" #include "Util/Random.h" #include "States/Playing_State.h" #include "States/Splash_Screen.h" #include "Game/Equipment/Equipment_Data.h" namespace { void calculateFPS() { static sf::Clock timer; static sf::Clock printTimer; static auto numFrames = 0; numFrames++; if (printTimer.getElapsedTime().asSeconds() >= 1.0f) { auto fps = (float)numFrames / timer.getElapsedTime().asSeconds(); printTimer.restart(); std::cout << fps << std::endl; numFrames = 0; timer.restart(); } } } Application::Application() { Display ::init ("Hero - V0.1"); Random ::init (); Equipment ::initData (m_resourceHolder); //pushState(std::make_unique<State::Splash_Screen>(*this)); pushState(std::make_unique<State::Playing>(*this)); } void Application::runMainLoop() { sf::Clock c; while (Display::isOpen()) { auto dt = c.restart().asSeconds(); Display::clear({50, 50, 100}); m_states.top()->input (); m_states.top()->update (dt); m_states.top()->draw (); Display::update (); calculateFPS (); Display::pollEvents(*m_states.top()); } } const Resource_Holder& Application::getResources() const { return m_resourceHolder; } void Application::pushState(std::unique_ptr<State::State_Base> state) { m_states.push(std::move(state)); } void Application::popState() { m_states.pop(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SlsRequestFactory.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-10-24 07:42:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_SLIDESORTER_REQUEST_FACTORY_HXX #define SD_SLIDESORTER_REQUEST_FACTORY_HXX #include "model/SlideSorterModel.hxx" #include "model/SlsPageDescriptor.hxx" #include "view/SlideSorterView.hxx" #include <svx/svdpagv.hxx> #include <svx/sdr/contact/viewcontact.hxx> namespace sd { namespace slidesorter { namespace view { class PageObjectViewObjectContact; } } } namespace sd { namespace slidesorter { namespace cache { template <class Queue, bool UseAheadOfTimeRequests> class RequestFactory { public: void operator() ( const model::SlideSorterModel& rModel, const view::SlideSorterView& rView, Queue& mrQueue); }; //============================================================================= // Implementation //===== RequestFactory ====================================================== template <class Queue,bool UseAheadOfTimeRequests> void RequestFactory<Queue,UseAheadOfTimeRequests>::operator() ( const model::SlideSorterModel& rModel, const view::SlideSorterView& rView, Queue& rQueue) { // Fill the queues with the new content. Visible page objects go into // the regular queue, non-visible page objects go into the ahead-of-time // queue. SdrPageView* pPageView = rView.GetPageViewPvNum(0); SdrPageViewWindow* pPageViewWindow = NULL; if (pPageView != NULL) pPageViewWindow = pPageView->GetWindow(0); if (pPageViewWindow != NULL) { ::sdr::contact::ObjectContact& rObjectContact ( rView.GetPageViewPvNum(0)->GetWindow(0)->GetObjectContact()); // Add the requests for the visible pages. model::SlideSorterModel::Enumeration aPageEnumeration ( rModel.GetVisiblePagesEnumeration()); while (aPageEnumeration.HasMoreElements()) { model::PageDescriptor& rDescriptor (aPageEnumeration.GetNextElement()); view::PageObjectViewObjectContact* pRequest (rDescriptor.GetViewObjectContact()); if (pRequest != NULL) rQueue.AddRequest(*pRequest, VISIBLE_NO_PREVIEW); } if (UseAheadOfTimeRequests) { // Add the requests for the non-visible pages. aPageEnumeration = rModel.GetAllPagesEnumeration(); while (aPageEnumeration.HasMoreElements()) { model::PageDescriptor& rDescriptor (aPageEnumeration.GetNextElement()); view::PageObjectViewObjectContact* pRequest = static_cast<view::PageObjectViewObjectContact*>( &rDescriptor.GetPageObject()->GetViewContact() .GetViewObjectContact(rObjectContact)); if ( ! rDescriptor.IsVisible()) rQueue.AddRequest(*pRequest, NOT_VISIBLE); } } } } } } } // end of namespace ::sd::slidesorter::cache #endif <commit_msg>INTEGRATION: CWS impress89 (1.4.120); FILE MERGED 2006/03/20 10:18:30 af 1.4.120.1: #132646# Using shared_ptr to slidesorter PageDescriptor.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SlsRequestFactory.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2006-04-06 16:18:13 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_SLIDESORTER_REQUEST_FACTORY_HXX #define SD_SLIDESORTER_REQUEST_FACTORY_HXX #include "model/SlideSorterModel.hxx" #include "model/SlsPageDescriptor.hxx" #include "view/SlideSorterView.hxx" #include <svx/svdpagv.hxx> #include <svx/sdr/contact/viewcontact.hxx> namespace sd { namespace slidesorter { namespace view { class PageObjectViewObjectContact; } } } namespace sd { namespace slidesorter { namespace cache { template <class Queue, bool UseAheadOfTimeRequests> class RequestFactory { public: void operator() ( const model::SlideSorterModel& rModel, const view::SlideSorterView& rView, Queue& mrQueue); }; //============================================================================= // Implementation //===== RequestFactory ====================================================== template <class Queue,bool UseAheadOfTimeRequests> void RequestFactory<Queue,UseAheadOfTimeRequests>::operator() ( const model::SlideSorterModel& rModel, const view::SlideSorterView& rView, Queue& rQueue) { // Fill the queues with the new content. Visible page objects go into // the regular queue, non-visible page objects go into the ahead-of-time // queue. SdrPageView* pPageView = rView.GetPageViewPvNum(0); SdrPageViewWindow* pPageViewWindow = NULL; if (pPageView != NULL) pPageViewWindow = pPageView->GetWindow(0); if (pPageViewWindow != NULL) { ::sdr::contact::ObjectContact& rObjectContact ( rView.GetPageViewPvNum(0)->GetWindow(0)->GetObjectContact()); // Add the requests for the visible pages. model::SlideSorterModel::Enumeration aPageEnumeration ( rModel.GetVisiblePagesEnumeration()); while (aPageEnumeration.HasMoreElements()) { model::SharedPageDescriptor pDescriptor (aPageEnumeration.GetNextElement()); view::PageObjectViewObjectContact* pRequest (pDescriptor->GetViewObjectContact()); if (pRequest != NULL) rQueue.AddRequest(*pRequest, VISIBLE_NO_PREVIEW); } if (UseAheadOfTimeRequests) { // Add the requests for the non-visible pages. aPageEnumeration = rModel.GetAllPagesEnumeration(); while (aPageEnumeration.HasMoreElements()) { model::SharedPageDescriptor pDescriptor (aPageEnumeration.GetNextElement()); view::PageObjectViewObjectContact* pRequest = static_cast<view::PageObjectViewObjectContact*>( &pDescriptor->GetPageObject()->GetViewContact() .GetViewObjectContact(rObjectContact)); if ( ! pDescriptor->IsVisible()) rQueue.AddRequest(*pRequest, NOT_VISIBLE); } } } } } } } // end of namespace ::sd::slidesorter::cache #endif <|endoftext|>
<commit_before><commit_msg>Bin obsolete pointless preprocessor trickery<commit_after><|endoftext|>
<commit_before>#pragma once #include <sse/schemes/tethys/types.hpp> #include <cstring> #include <array> #include <istream> #include <ostream> namespace sse { namespace tethys { namespace encoders { template<class Key, class T, size_t PAGESIZE> struct EncodeSeparateEncoder { static constexpr size_t kAdditionalKeyEntriesPerList = sizeof(Key) / sizeof(T) + (sizeof(Key) % sizeof(T) == 0 ? 0 : 1); static constexpr size_t kListLengthEntriesNumber = sizeof(TethysAssignmentInfo::list_length) / sizeof(T) + (sizeof(TethysAssignmentInfo::list_length) % sizeof(T) == 0 ? 0 : 1); static constexpr size_t kListControlValues = 2 * (kAdditionalKeyEntriesPerList + kListLengthEntriesNumber); static constexpr size_t kBucketControlValues = 1; size_t start_block_encoding(uint8_t* buffer, size_t table_index) { (void)buffer; (void)table_index; return 0; } size_t encode(uint8_t* buffer, size_t table_index, const Key& key, const std::vector<T>& values, TethysAssignmentInfo infos) { (void)table_index; if (infos.assigned_list_length < kAdditionalKeyEntriesPerList + kListLengthEntriesNumber) { return 0; // // for debugging only, not a valid encoding // // std::fill( // // buffer, buffer + infos.assigned_list_length * // sizeof(T), 0xDD); // // return infos.assigned_list_length * sizeof(T); } uint64_t original_list_size = infos.list_length - kListControlValues; // we have to pay attention to the difference between the allocated list // size and the values' list size uint64_t encoded_list_size = infos.assigned_list_length - (kAdditionalKeyEntriesPerList + kListLengthEntriesNumber); // we know this is positive // because of the previous test // be sure we do not overflow the original list length by considering // spilled control values encoded_list_size = std::min(encoded_list_size, original_list_size); auto sublist_begin = values.begin(); auto sublist_end = values.end(); // size_t sublist_begin = 0; // size_t sublist_end = values.size(); // the elements in the list are encoded the following order: // IncomingEdge || Stashed Edge || Outgoing Edge if (infos.edge_orientation == IncomingEdge) { sublist_end = values.begin() + encoded_list_size; // sublist_end = encoded_list_size; } else { sublist_begin = values.end() - encoded_list_size; // sublist_begin = values.size() - encoded_list_size; } size_t offset = 0; // copy the length of the list std::copy(reinterpret_cast<const uint8_t*>(&encoded_list_size), reinterpret_cast<const uint8_t*>(&encoded_list_size) + sizeof(encoded_list_size), buffer + offset); offset += sizeof(encoded_list_size); // offset = 8 // fill with dummy bytes if needed std::fill(buffer + offset, buffer + kAdditionalKeyEntriesPerList * sizeof(T), 0x11); offset = kListLengthEntriesNumber * sizeof(T); // offset = 8 // copy the key std::copy(reinterpret_cast<const uint8_t*>(&key), reinterpret_cast<const uint8_t*>(&key) + sizeof(Key), buffer + offset); offset += sizeof(Key); // offset = 24 // fill with dummy bytes if needed std::fill( buffer + offset, buffer + kListControlValues * sizeof(T), 0x22); offset = (kAdditionalKeyEntriesPerList + kListLengthEntriesNumber) * sizeof(T); // offset = 24 // now copy the values for (auto it = sublist_begin; it != sublist_end; ++it) { const T& v = *it; std::copy(reinterpret_cast<const uint8_t*>(&v), reinterpret_cast<const uint8_t*>(&v) + sizeof(T), buffer + offset); offset += sizeof(T); } // // for debugging, paint the remaining with an other patter // // this is a not a valid encoding // std::fill(buffer + offset, // buffer + infos.assigned_list_length * sizeof(T), // 0xDD); // return infos.assigned_list_length * sizeof(T); return offset; } size_t finish_block_encoding(uint8_t* buffer, size_t table_index, size_t written_bytes, size_t remaining_bytes) { (void)table_index; if (remaining_bytes == 0) { return 0; } memset(buffer + written_bytes, 0x00, remaining_bytes); return remaining_bytes; } void serialize_key_value(std::ostream& out, const Key& k, const TethysStashSerializationValue<T>& v) { bool bucket_1_uf = (v.assignement_info.assigned_list_length < (kAdditionalKeyEntriesPerList + kListLengthEntriesNumber)); bool bucket_2_uf = (v.assignement_info.dual_assigned_list_length < (kAdditionalKeyEntriesPerList + kListLengthEntriesNumber)); size_t encoded_list_size_1 = 0; size_t encoded_list_size_2 = 0; if (!bucket_1_uf) { encoded_list_size_1 = v.assignement_info.assigned_list_length - (kAdditionalKeyEntriesPerList + kListLengthEntriesNumber); } if (!bucket_2_uf) { encoded_list_size_2 = v.assignement_info.dual_assigned_list_length - (kAdditionalKeyEntriesPerList + kListLengthEntriesNumber); // we know this is // positive because of the // previous test } uint64_t original_list_size = v.assignement_info.list_length - kListControlValues; // be sure we do not overflow the original list length by considering // spilled control values encoded_list_size_1 = std::min(encoded_list_size_1, original_list_size); encoded_list_size_2 = std::min(encoded_list_size_2, original_list_size); uint64_t v_size = v.assignement_info.list_length - kListControlValues - encoded_list_size_1 - encoded_list_size_2; if (v_size == 0) { return; } // write the key out.write(reinterpret_cast<const char*>(k.data()), k.size()); // write the size of the vector out.write(reinterpret_cast<const char*>(&v_size), sizeof(v_size)); // and the elements // for (auto it = v.data->begin() + encoded_list_size_1; // it != v.data->end() - encoded_list_size_2; // ++it) { const std::vector<T>& values = *(v.data); for (size_t i = encoded_list_size_1; i < values.size() - encoded_list_size_2; i++) { const T& elt = values[i]; out.write(reinterpret_cast<const char*>(&elt), sizeof(elt)); } } void start_tethys_encoding(const details::TethysGraph&) { } void finish_tethys_table_encoding() { } void finish_tethys_encoding() { } }; template<class Key, class T, size_t PAGESIZE> struct EncodeSeparateDecoder { static constexpr size_t kAdditionalKeyEntriesPerList = EncodeSeparateEncoder<Key, T, PAGESIZE>::kAdditionalKeyEntriesPerList; static constexpr size_t kListLengthEntriesNumber = EncodeSeparateEncoder<Key, T, PAGESIZE>::kListLengthEntriesNumber; static constexpr size_t kListControlValues = EncodeSeparateEncoder<Key, T, PAGESIZE>::kListControlValues; void decode_single_bucket(const Key& key, const std::array<uint8_t, PAGESIZE>& bucket, std::vector<T>& results) const { size_t offset = 0; Key list_key; uint64_t list_length; while (offset < bucket.size()) { // read the length of the list memcpy(&list_length, bucket.data() + offset, sizeof(list_length)); offset += sizeof(list_length); if (list_length == 0) { // we are at the end of the bucket break; } // read the key of the current list memcpy(&list_key, bucket.data() + offset, sizeof(list_key)); offset += sizeof(list_key); if (list_key == key) { // match on the key results.reserve(results.size() + list_length); for (size_t i = 0; i < list_length; i++) { T value; memcpy(&value, bucket.data() + offset, sizeof(value)); offset += sizeof(value); results.push_back(value); } break; } else { // jump to the next list offset += list_length * sizeof(T); } } } std::vector<T> decode_buckets(const Key& key, const std::array<uint8_t, PAGESIZE>& bucket_0, size_t, const std::array<uint8_t, PAGESIZE>& bucket_1, size_t) { std::vector<T> res; decode_single_bucket(key, bucket_0, res); decode_single_bucket(key, bucket_1, res); return res; } std::pair<Key, std::vector<T>> deserialize_key_value(std::istream& in) { Key k; uint64_t v_size = 0; std::vector<T> v; in.read(reinterpret_cast<char*>(&k), sizeof(k)); // read the size of the vector in.read(reinterpret_cast<char*>(&v_size), sizeof(v_size)); v.reserve(v_size); for (size_t i = 0; i < v_size; i++) { T elt; in.read(reinterpret_cast<char*>(&elt), sizeof(elt)); v.push_back(elt); } return std::make_pair(k, v); } }; } // namespace encoders } // namespace tethys } // namespace sse<commit_msg>Bugfix: inval border condition when encoding lists Buckets which have been allocated just enough elements to contain the list's key and its length cannot contain any actual data. Skip serialization in that case.<commit_after>#pragma once #include <sse/schemes/tethys/types.hpp> #include <cassert> #include <cstring> #include <array> #include <istream> #include <ostream> namespace sse { namespace tethys { namespace encoders { template<class Key, class T, size_t PAGESIZE> struct EncodeSeparateEncoder { static constexpr size_t kAdditionalKeyEntriesPerList = sizeof(Key) / sizeof(T) + (sizeof(Key) % sizeof(T) == 0 ? 0 : 1); static constexpr size_t kListLengthEntriesNumber = sizeof(TethysAssignmentInfo::list_length) / sizeof(T) + (sizeof(TethysAssignmentInfo::list_length) % sizeof(T) == 0 ? 0 : 1); static constexpr size_t kListControlValues = 2 * (kAdditionalKeyEntriesPerList + kListLengthEntriesNumber); static constexpr size_t kBucketControlValues = 1; size_t start_block_encoding(uint8_t* buffer, size_t table_index) { (void)buffer; (void)table_index; return 0; } size_t encode(uint8_t* buffer, size_t table_index, const Key& key, const std::vector<T>& values, TethysAssignmentInfo infos) { (void)table_index; if (infos.assigned_list_length <= kAdditionalKeyEntriesPerList + kListLengthEntriesNumber) { return 0; // // for debugging only, not a valid encoding // // std::fill( // // buffer, buffer + infos.assigned_list_length * // sizeof(T), 0xDD); // // return infos.assigned_list_length * sizeof(T); } uint64_t original_list_size = infos.list_length - kListControlValues; // we have to pay attention to the difference between the allocated list // size and the values' list size uint64_t encoded_list_size = infos.assigned_list_length - (kAdditionalKeyEntriesPerList + kListLengthEntriesNumber); // we know this is positive // because of the previous test // be sure we do not overflow the original list length by considering // spilled control values encoded_list_size = std::min(encoded_list_size, original_list_size); auto sublist_begin = values.begin(); auto sublist_end = values.end(); // size_t sublist_begin = 0; // size_t sublist_end = values.size(); // the elements in the list are encoded the following order: // IncomingEdge || Stashed Edge || Outgoing Edge if (infos.edge_orientation == IncomingEdge) { sublist_end = values.begin() + encoded_list_size; // sublist_end = encoded_list_size; } else { sublist_begin = values.end() - encoded_list_size; // sublist_begin = values.size() - encoded_list_size; } size_t offset = 0; // copy the length of the list std::copy(reinterpret_cast<const uint8_t*>(&encoded_list_size), reinterpret_cast<const uint8_t*>(&encoded_list_size) + sizeof(encoded_list_size), buffer + offset); offset += sizeof(encoded_list_size); // offset = 8 // fill with dummy bytes if needed if (offset < kListLengthEntriesNumber * sizeof(T)) { std::fill(buffer + offset, buffer + kAdditionalKeyEntriesPerList * sizeof(T), 0x11); offset = kListLengthEntriesNumber * sizeof(T); // offset = 8 } // copy the key std::copy(reinterpret_cast<const uint8_t*>(&key), reinterpret_cast<const uint8_t*>(&key) + sizeof(Key), buffer + offset); offset += sizeof(Key); // offset = 24 // fill with dummy bytes if needed if (offset < (kAdditionalKeyEntriesPerList + kListLengthEntriesNumber) * sizeof(T)) { std::fill( buffer + offset, buffer + kListControlValues * sizeof(T), 0x22); offset = (kAdditionalKeyEntriesPerList + kListLengthEntriesNumber) * sizeof(T); // offset = 24 } // now copy the values for (auto it = sublist_begin; it != sublist_end; ++it) { const T& v = *it; std::copy(reinterpret_cast<const uint8_t*>(&v), reinterpret_cast<const uint8_t*>(&v) + sizeof(T), buffer + offset); offset += sizeof(T); } // // for debugging, paint the remaining with an other patter // // this is a not a valid encoding // std::fill(buffer + offset, // buffer + infos.assigned_list_length * sizeof(T), // 0xDD); // return infos.assigned_list_length * sizeof(T); // std::cerr << offset << " / " << infos.list_length * sizeof(T) << // "\n"; // assert(offset <= infos.list_length * sizeof(T)); return offset; } size_t finish_block_encoding(uint8_t* buffer, size_t table_index, size_t written_bytes, size_t remaining_bytes) { (void)table_index; if (remaining_bytes == 0) { return 0; } memset(buffer + written_bytes, 0x00, remaining_bytes); return remaining_bytes; } void serialize_key_value(std::ostream& out, const Key& k, const TethysStashSerializationValue<T>& v) { bool bucket_1_uf = (v.assignement_info.assigned_list_length <= (kAdditionalKeyEntriesPerList + kListLengthEntriesNumber)); bool bucket_2_uf = (v.assignement_info.dual_assigned_list_length <= (kAdditionalKeyEntriesPerList + kListLengthEntriesNumber)); size_t encoded_list_size_1 = 0; size_t encoded_list_size_2 = 0; if (!bucket_1_uf) { encoded_list_size_1 = v.assignement_info.assigned_list_length - (kAdditionalKeyEntriesPerList + kListLengthEntriesNumber); } if (!bucket_2_uf) { encoded_list_size_2 = v.assignement_info.dual_assigned_list_length - (kAdditionalKeyEntriesPerList + kListLengthEntriesNumber); // we know this is // positive because of the // previous test } uint64_t original_list_size = v.assignement_info.list_length - kListControlValues; // be sure we do not overflow the original list length by considering // spilled control values encoded_list_size_1 = std::min(encoded_list_size_1, original_list_size); encoded_list_size_2 = std::min(encoded_list_size_2, original_list_size); uint64_t v_size = v.assignement_info.list_length - kListControlValues - encoded_list_size_1 - encoded_list_size_2; if (v_size == 0) { return; } // write the key out.write(reinterpret_cast<const char*>(k.data()), k.size()); // write the size of the vector out.write(reinterpret_cast<const char*>(&v_size), sizeof(v_size)); // and the elements // for (auto it = v.data->begin() + encoded_list_size_1; // it != v.data->end() - encoded_list_size_2; // ++it) { const std::vector<T>& values = *(v.data); for (size_t i = encoded_list_size_1; i < values.size() - encoded_list_size_2; i++) { const T& elt = values[i]; out.write(reinterpret_cast<const char*>(&elt), sizeof(elt)); } } void start_tethys_encoding(const details::TethysGraph&) { } void finish_tethys_table_encoding() { } void finish_tethys_encoding() { } }; template<class Key, class T, size_t PAGESIZE> struct EncodeSeparateDecoder { static constexpr size_t kAdditionalKeyEntriesPerList = EncodeSeparateEncoder<Key, T, PAGESIZE>::kAdditionalKeyEntriesPerList; static constexpr size_t kListLengthEntriesNumber = EncodeSeparateEncoder<Key, T, PAGESIZE>::kListLengthEntriesNumber; static constexpr size_t kListControlValues = EncodeSeparateEncoder<Key, T, PAGESIZE>::kListControlValues; void decode_single_bucket(const Key& key, const std::array<uint8_t, PAGESIZE>& bucket, std::vector<T>& results) const { size_t offset = 0; Key list_key; uint64_t list_length; while (offset < bucket.size()) { // read the length of the list memcpy(&list_length, bucket.data() + offset, sizeof(list_length)); offset += sizeof(list_length); if (list_length == 0) { // we are at the end of the bucket break; } // read the key of the current list memcpy(&list_key, bucket.data() + offset, sizeof(list_key)); offset += sizeof(list_key); if (list_key == key) { // match on the key results.reserve(results.size() + list_length); for (size_t i = 0; i < list_length; i++) { T value; memcpy(&value, bucket.data() + offset, sizeof(value)); offset += sizeof(value); results.push_back(value); } break; } else { // jump to the next list offset += list_length * sizeof(T); } } } std::vector<T> decode_buckets(const Key& key, const std::array<uint8_t, PAGESIZE>& bucket_0, size_t, const std::array<uint8_t, PAGESIZE>& bucket_1, size_t) { std::vector<T> res; decode_single_bucket(key, bucket_0, res); decode_single_bucket(key, bucket_1, res); return res; } std::pair<Key, std::vector<T>> deserialize_key_value(std::istream& in) { Key k; uint64_t v_size = 0; std::vector<T> v; in.read(reinterpret_cast<char*>(&k), sizeof(k)); // read the size of the vector in.read(reinterpret_cast<char*>(&v_size), sizeof(v_size)); v.reserve(v_size); for (size_t i = 0; i < v_size; i++) { T elt; in.read(reinterpret_cast<char*>(&elt), sizeof(elt)); v.push_back(elt); } return std::make_pair(k, v); } }; } // namespace encoders } // namespace tethys } // namespace sse<|endoftext|>
<commit_before>/** \copyright * Copyright (c) 2015, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file client.cxx * * A fake application meant to be compiled into a .js library. This library can * be included in html pages to add an OpenLCB stack running in the browser. * * @author Balazs Racz * @date 13 Sep 2015 */ #include <emscripten.h> #include <emscripten/bind.h> #include <emscripten/val.h> #include <memory> #include <set> #include "os/os.h" #include "can_frame.h" #include "nmranet_config.h" #include "os/TempFile.hxx" #include "openlcb/Defs.hxx" #include "openlcb/SimpleStack.hxx" #include "openlcb/SimpleNodeInfoMockUserFile.hxx" #include "openlcb/EventHandlerTemplates.hxx" #include "utils/JSWebsocketClient.hxx" const openlcb::NodeID NODE_ID = 0x0501010114DFULL; openlcb::SimpleCanStack stack(NODE_ID); openlcb::MockSNIPUserFile snip_user_file( "Javascript app", "No description"); const char *const openlcb::SNIP_DYNAMIC_FILENAME = openlcb::MockSNIPUserFile::snip_user_file_path; bool stack_started = false; void ignore_function() { } class QueryFlow : public StateFlowBase { public: QueryFlow() : StateFlowBase(stack.service()) { start_flow(STATE(wait_for_initialized)); } /// Adds an event ID to be queried (once the node is up). void add_event(uint64_t event_id) { /// @TODO (balazs.racz) handle the case when events are inserted after /// the iteration has begun. events_.insert(event_id); } /// Starts the entire initialization again, performing a query on all known /// event IDs once more. void restart() { if (is_terminated()) { start_flow(STATE(wait_for_initialized)); } else { nextEvent_ = events_.begin(); } } private: Action wait_for_initialized() { if (!stack.node()->is_initialized()) { return sleep_and_call( &timer_, MSEC_TO_NSEC(100), STATE(wait_for_initialized)); } return call_immediately(STATE(start_iteration)); } Action start_iteration() { nextEvent_ = events_.begin(); return call_immediately(STATE(iterate)); } Action iterate() { if (nextEvent_ == events_.end()) { return exit(); } return allocate_and_call( stack.node()->iface()->global_message_write_flow(), STATE(send_query)); } Action send_query() { auto *f = stack.node()->iface()->global_message_write_flow(); auto *b = get_allocation_result(f); b->data()->reset(openlcb::Defs::MTI_PRODUCER_IDENTIFY, stack.node()->node_id(), openlcb::eventid_to_buffer(*nextEvent_)); b->data()->set_flag_dst(openlcb::GenMessage::WAIT_FOR_LOCAL_LOOPBACK); b->set_done(n_.reset(this)); f->send(b); nextEvent_++; return wait_and_call(STATE(delay_before_iterate)); } Action delay_before_iterate() { return sleep_and_call(&timer_, MSEC_TO_NSEC(5), STATE(iterate)); } using EventList = std::set<uint64_t>; EventList events_; EventList::iterator nextEvent_; BarrierNotifiable n_; StateFlowTimer timer_{this}; } g_query_flow; class JSBitEventPC : private openlcb::BitEventInterface { public: JSBitEventPC(std::string event_on, emscripten::val fn_on_cb, std::string event_off, emscripten::val fn_off_cb) : BitEventInterface(parse_event_id(event_on), parse_event_id(event_off)) , eventOnCallback_(fn_on_cb) , eventOffCallback_(fn_off_cb) , consumer_(this) { g_query_flow.add_event(BitEventInterface::event_on()); } void toggleState() { if (!hasValue_) { lastValue_ = true; hasValue_ = true; //return; } /// @TODO(balazs.racz) ideally we should be able to just call /// SendEventReport. However, that requires a WriteHelper and there is /// no option to allocate a buffer dynamically. lastValue_ = !lastValue_; auto *f = stack.node()->iface()->global_message_write_flow(); auto *b = f->alloc(); b->data()->reset(openlcb::Defs::MTI_EVENT_REPORT, stack.node()->node_id(), openlcb::eventid_to_buffer(lastValue_ ? event_on() : event_off())); f->send(b); } private: static uint64_t parse_event_id(const string &s) { return strtoll(s.c_str(), nullptr, 16); } openlcb::Node *node() OVERRIDE { return stack.node(); } void set_state(bool new_value) OVERRIDE { lastValue_ = new_value; hasValue_ = true; if (new_value) { eventOnCallback_(); } else { eventOffCallback_(); } } openlcb::EventState get_current_state() OVERRIDE { using openlcb::EventState; if (!hasValue_) return EventState::UNKNOWN; return lastValue_ ? EventState::VALID : EventState::INVALID; } bool hasValue_{false}; bool lastValue_{false}; emscripten::val eventOnCallback_; emscripten::val eventOffCallback_; openlcb::BitEventPC consumer_; }; void start_stack() { if (!stack_started) { stack_started = true; emscripten_cancel_main_loop(); stack.loop_executor(); EM_ASM(console.log('stack start done');); } else { // Restarting. stack.restart_stack(); g_query_flow.restart(); } } /** Entry point to application. * @param argc number of command line arguments * @param argv array of command line arguments * @return 0, should never return */ int appl_main(int argc, char *argv[]) { new JSWebsocketClient(stack.can_hub(), "openmrn_websocket_server_url"); // We delay the start of the stack until the connection is established. emscripten_set_main_loop(&ignore_function, 0, true); return 0; } EMSCRIPTEN_BINDINGS(js_client_main) { emscripten::function("startStack", &start_stack); emscripten::class_<JSBitEventPC>("BitEventPC") .constructor<std::string, emscripten::val, std::string, emscripten::val>() .function("toggleState", &JSBitEventPC::toggleState); } <commit_msg>Adds exported functions for adding various hub-like options.<commit_after>/** \copyright * Copyright (c) 2015, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file client.cxx * * A fake application meant to be compiled into a .js library. This library can * be included in html pages to add an OpenLCB stack running in the browser. * * @author Balazs Racz * @date 13 Sep 2015 */ #include <emscripten.h> #include <emscripten/bind.h> #include <emscripten/val.h> #include <memory> #include <set> #include "os/os.h" #include "can_frame.h" #include "nmranet_config.h" #include "os/TempFile.hxx" #include "openlcb/Defs.hxx" #include "openlcb/SimpleStack.hxx" #include "openlcb/SimpleNodeInfoMockUserFile.hxx" #include "openlcb/EventHandlerTemplates.hxx" #include "utils/JSWebsocketClient.hxx" #include "utils/JSTcpClient.hxx" #include "utils/JSTcpHub.hxx" #include "utils/JSWebsocketServer.hxx" const openlcb::NodeID NODE_ID = 0x0501010114DFULL; openlcb::SimpleCanStack stack(NODE_ID); openlcb::MockSNIPUserFile snip_user_file( "Javascript app", "No description"); const char *const openlcb::SNIP_DYNAMIC_FILENAME = openlcb::MockSNIPUserFile::snip_user_file_path; bool stack_started = false; void ignore_function() { } class QueryFlow : public StateFlowBase { public: QueryFlow() : StateFlowBase(stack.service()) { start_flow(STATE(wait_for_initialized)); } /// Adds an event ID to be queried (once the node is up). void add_event(uint64_t event_id) { /// @TODO (balazs.racz) handle the case when events are inserted after /// the iteration has begun. events_.insert(event_id); } /// Starts the entire initialization again, performing a query on all known /// event IDs once more. void restart() { if (is_terminated()) { start_flow(STATE(wait_for_initialized)); } else { nextEvent_ = events_.begin(); } } private: Action wait_for_initialized() { if (!stack.node()->is_initialized()) { return sleep_and_call( &timer_, MSEC_TO_NSEC(100), STATE(wait_for_initialized)); } return call_immediately(STATE(start_iteration)); } Action start_iteration() { nextEvent_ = events_.begin(); return call_immediately(STATE(iterate)); } Action iterate() { if (nextEvent_ == events_.end()) { return exit(); } return allocate_and_call( stack.node()->iface()->global_message_write_flow(), STATE(send_query)); } Action send_query() { auto *f = stack.node()->iface()->global_message_write_flow(); auto *b = get_allocation_result(f); b->data()->reset(openlcb::Defs::MTI_PRODUCER_IDENTIFY, stack.node()->node_id(), openlcb::eventid_to_buffer(*nextEvent_)); b->data()->set_flag_dst(openlcb::GenMessage::WAIT_FOR_LOCAL_LOOPBACK); b->set_done(n_.reset(this)); f->send(b); nextEvent_++; return wait_and_call(STATE(delay_before_iterate)); } Action delay_before_iterate() { return sleep_and_call(&timer_, MSEC_TO_NSEC(5), STATE(iterate)); } using EventList = std::set<uint64_t>; EventList events_; EventList::iterator nextEvent_; BarrierNotifiable n_; StateFlowTimer timer_{this}; } g_query_flow; class JSBitEventPC : private openlcb::BitEventInterface { public: JSBitEventPC(std::string event_on, emscripten::val fn_on_cb, std::string event_off, emscripten::val fn_off_cb) : BitEventInterface(parse_event_id(event_on), parse_event_id(event_off)) , eventOnCallback_(fn_on_cb) , eventOffCallback_(fn_off_cb) , consumer_(this) { g_query_flow.add_event(BitEventInterface::event_on()); } void toggleState() { if (!hasValue_) { lastValue_ = true; hasValue_ = true; //return; } /// @TODO(balazs.racz) ideally we should be able to just call /// SendEventReport. However, that requires a WriteHelper and there is /// no option to allocate a buffer dynamically. lastValue_ = !lastValue_; auto *f = stack.node()->iface()->global_message_write_flow(); auto *b = f->alloc(); b->data()->reset(openlcb::Defs::MTI_EVENT_REPORT, stack.node()->node_id(), openlcb::eventid_to_buffer(lastValue_ ? event_on() : event_off())); f->send(b); } private: static uint64_t parse_event_id(const string &s) { return strtoll(s.c_str(), nullptr, 16); } openlcb::Node *node() OVERRIDE { return stack.node(); } void set_state(bool new_value) OVERRIDE { lastValue_ = new_value; hasValue_ = true; if (new_value) { eventOnCallback_(); } else { eventOffCallback_(); } } openlcb::EventState get_current_state() OVERRIDE { using openlcb::EventState; if (!hasValue_) return EventState::UNKNOWN; return lastValue_ ? EventState::VALID : EventState::INVALID; } bool hasValue_{false}; bool lastValue_{false}; emscripten::val eventOnCallback_; emscripten::val eventOffCallback_; openlcb::BitEventPC consumer_; }; void start_stack() { if (!stack_started) { stack_started = true; emscripten_cancel_main_loop(); stack.loop_executor(); EM_ASM(console.log('stack start done');); } else { // Restarting. stack.restart_stack(); g_query_flow.restart(); } } /** Entry point to application. * @param argc number of command line arguments * @param argv array of command line arguments * @return 0, should never return */ int appl_main(int argc, char *argv[]) { new JSWebsocketClient(stack.can_hub(), "openmrn_websocket_server_url"); // We delay the start of the stack until the connection is established. emscripten_set_main_loop(&ignore_function, 0, true); return 0; } /// Adds a new connection to the hub, connecting to a remote hub via TCP /// gridconnect protocol. /// @param host is the host name or IP address to connect to. /// @param port is the TCP port number void add_tcp_client(string host, int port) { new JSTcpClient(stack.can_hub(), host, port); } /// Adds a new connection to the hub, connecting to a remote websocket server /// via the gridconnect-over-websocket protocol. /// @param url address of the websocket server. void add_websocket_client(string url) { new JSWebsocketClient(stack.can_hub(), url); } /// Starts a server listening to a TCP port for incoming gridconnect-over-TCP /// connections. /// @param port port number to listen on (usually 12021) void start_tcp_hub(int port) { new JSTcpHub(stack.can_hub(), port); } /// Starts a server listening to a TCP port for incoming HTTP to websocket /// connections. The websocket connections use gridconnect-over-websocket to /// connect to the LCC network. /// @param port port number to listen on /// @param static_dir files in this directory will be available on the HTTP /// server started on the given port. Can be html pages (e.g. panels) and js /// script in there. void start_websocket_server(int port, string static_dir) { new JSWebsocketServer(stack.can_hub(), port, static_dir); } EMSCRIPTEN_BINDINGS(js_client_main) { emscripten::function("startStack", &start_stack); emscripten::class_<JSBitEventPC>("BitEventPC") .constructor<std::string, emscripten::val, std::string, emscripten::val>() .function("toggleState", &JSBitEventPC::toggleState); emscripten::function("startWebsocketServer", &start_websocket_server); emscripten::function("startTcpHub", &start_tcp_hub); emscripten::function("addWebsocketClient", &add_websocket_client); emscripten::function("addTcpClient", &add_tcp_client); } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2016-2020, Natalnet Laboratory for Perceptual Robotics * All rights reserved. * Redistribution and use in source and binary forms, with or without modification, are permitted * provided * that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and * the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and * the following disclaimer in the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Author: * * Bruno Silva */ // C++ #include <cstdio> #include <cstdlib> #include <vector> // C++ Third Party #include <Eigen/Geometry> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> // RGBD RTK #include <config_loader.h> #include <event_logger.h> #include <geometry.h> #include <marker_finder.h> #include <optical_flow_visual_odometry.h> #include <reconstruction_visualizer.h> #include <rgbd_loader.h> #include <slam_solver.h> using namespace std; using namespace cv; using namespace aruco; struct Pose { int id; float x; float y; float z; float x_rotation; float y_rotation; float z_rotation; float w_rotation; }; /** * Adds vertix and edges in slam_solver and visualizer * @param new_keyframe_pose new keyframe that should be added * @param last_keyframe_pose the last keyframe added in graph, this is update this in this function * @param first_keyframe_pose the first keyframe * @param num_keyframes number of keyframes in graph, this is update in this function * @param slam_solver slam_solver reference * @param visualizer visualizer reference * @param is_loop_closure if the vertex added is a loop_closure as well */ void addVertixAndEdge( Eigen::Affine3f cam_pose, Eigen::Affine3f& last_keyframe_pose, Eigen::Affine3f aruco_pose, int& num_keyframes, SLAM_Solver& slam_solver, ReconstructionVisualizer& visualizer, bool is_loop_closure); /** * This program shows the use of camera pose estimation using optical flow visual odometry. * @param .yml config. file (from which index_file is used) */ int main(int argc, char** argv) { int num_keyframes = 0; bool slam_solver_started = false; float marker_size, aruco_max_distance; string camera_calibration_file, aruco_dic, index_file; EventLogger& logger = EventLogger::getInstance(); logger.setVerbosityLevel(EventLogger::L_ERROR); SLAM_Solver slam_solver; ReconstructionVisualizer visualizer; Intrinsics intr(0); OpticalFlowVisualOdometry vo(intr); MarkerFinder marker_finder; RGBDLoader loader; Mat frame, depth; Eigen::Affine3f last_keyframe_pose; Eigen::Affine3f first_keyframe_pose; // Slam solver will start when the marker is found for the first time if (argc != 2) { logger.print( EventLogger::L_ERROR, "[slam_solver_test.cpp] Usage: %s <path/to/config_file.yaml>\n", argv[0]); exit(0); } ConfigLoader param_loader(argv[1]); param_loader.checkAndGetString("index_file", index_file); param_loader.checkAndGetFloat("aruco_marker_size", marker_size); param_loader.checkAndGetFloat("aruco_max_distance", aruco_max_distance); param_loader.checkAndGetString("camera_calibration_file", camera_calibration_file); param_loader.checkAndGetString("aruco_dic", aruco_dic); marker_finder.markerParam(camera_calibration_file, marker_size, aruco_dic); loader.processFile(index_file); // Compute visual odometry on each image for (int i = 0; i < loader.num_images_; i++) { // Load RGB-D image loader.getNextImage(frame, depth); // If aruco is not found yet if (slam_solver_started == false) { marker_finder.detectMarkersPoses( frame, Eigen::Affine3f::Identity(), aruco_max_distance); for (size_t i = 0; i < marker_finder.markers_.size(); i++) { // THIS SHOULD NOT BE HERE, THE ONLY REASON IS HERE IS BECAUSE I'M TESTING // A PROGRAM THAT SHOULD USE ONLY ONE MARKER IN A DATASET WITH MULTIPLE MARKERS if (250 == marker_finder.markers_[i].id) { // If we found the mark for the first time, we will add the marker as the origin // of the system Then we add the first camera pose related to the marker pose. // Getting Camera Pose vo.pose_ = marker_finder.marker_poses_[i]; // Adding first pose to slam_solver and visualizer slam_solver.addVertexAndEdge(vo.pose_, num_keyframes); visualizer.addReferenceFrame(vo.pose_, to_string(num_keyframes)); num_keyframes++; // Increment the number of keyframes found // Set slam solver started to true since we found the marker for the first time slam_solver_started = true; first_keyframe_pose = vo.pose_; last_keyframe_pose = vo.pose_; } } continue; } // If we have already found the marker we start the keyframe process else { marker_finder.detectMarkersPoses(frame, vo.pose_, aruco_max_distance); for (size_t i = 0; i < marker_finder.markers_.size(); i++) { if (250 == marker_finder.markers_[i].id) { addVertixAndEdge( vo.pose_, marker_finder.marker_poses_[i], last_keyframe_pose, num_keyframes, slam_solver, visualizer, true); } } // Estimate current camera pose bool is_kf = vo.computeCameraPose(frame, depth); // View tracked points for (size_t k = 0; k < vo.tracker_.curr_pts_.size(); k++) { Point2i pt1 = vo.tracker_.prev_pts_[k]; Point2i pt2 = vo.tracker_.curr_pts_[k]; Scalar color; is_kf ? color = CV_RGB(255, 0, 0) : color = CV_RGB(0, 0, 255); circle(frame, pt1, 1, color, -1); circle(frame, pt2, 3, color, -1); line(frame, pt1, pt2, color); } visualizer.viewReferenceFrame(vo.pose_); visualizer.viewQuantizedPointCloud(vo.curr_dense_cloud_, 0.05, vo.pose_); visualizer.addQuantizedPointCloud(vo.curr_dense_cloud_, 0.05, vo.pose_); // If we found a keyframe we will added to slam solver and visualizer if (is_kf) { addVertixAndEdge( vo.pose_, last_keyframe_pose, Eigen::Affine3f::Identity(), num_keyframes, slam_solver, visualizer, false); } } visualizer.spinOnce(); imshow("Image view", frame); // imshow("Depth view", depth); char key = waitKey(1); if (key == 27 || key == 'q' || key == 'Q') { logger.print(EventLogger::L_INFO, "[slam_solver_test.cpp] Exiting\n", argv[0]); break; } } slam_solver.optimizeGraph(10); // visualizer.spin(); return 0; } void addVertixAndEdge( Eigen::Affine3f cam_pose, Eigen::Affine3f& last_keyframe_pose, Eigen::Affine3f aruco_pose, int& num_keyframes, SLAM_Solver& slam_solver, ReconstructionVisualizer& visualizer, bool is_loop_closure) { double x = pow(cam_pose(0, 3) - last_keyframe_pose(0, 3), 2); double y = pow(cam_pose(1, 3) - last_keyframe_pose(1, 3), 2); double z = pow(cam_pose(2, 3) - last_keyframe_pose(2, 3), 2); // We will only add a new keyframe if they have at least 20cm of distance between each other if (sqrt(x + y + z) >= 0.2) { // Adding keyframe in visualizer visualizer.addReferenceFrame(cam_pose, to_string(num_keyframes)); // Add the keyframe and creating an edge to the last vertex slam_solver.addVertexAndEdge(cam_pose, num_keyframes); visualizer.addEdge(slam_solver.odometry_edges_.back()); // If the keyframe is a loop closure we will create a loop closing edge if (is_loop_closure == true) { // Adding the loop closing edge that is an edge from this vertex to the initial // If we want to change the system coord from A to B -> A.inverse * B slam_solver.addLoopClosingEdge(cam_pose.inverse() * aruco_pose, num_keyframes); visualizer.addEdge(slam_solver.loop_edges_.back(), Eigen::Vector3f(1.0, 0.0, 0.0)); } num_keyframes++; // Increment the number of keyframes found last_keyframe_pose = cam_pose; // Updating the pose of last keyframe } }<commit_msg>Fixing issue when adding loop closure edge(I was switching two parameters when calling the function to add the vertix and edge) and implementing 'online' optimization every 20 poses<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2016-2020, Natalnet Laboratory for Perceptual Robotics * All rights reserved. * Redistribution and use in source and binary forms, with or without modification, are permitted * provided * that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and * the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and * the following disclaimer in the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Author: * * Bruno Silva */ // C++ #include <cstdio> #include <cstdlib> #include <vector> // C++ Third Party #include <Eigen/Geometry> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> // RGBD RTK #include <config_loader.h> #include <event_logger.h> #include <geometry.h> #include <marker_finder.h> #include <optical_flow_visual_odometry.h> #include <reconstruction_visualizer.h> #include <rgbd_loader.h> #include <slam_solver.h> using namespace std; using namespace cv; using namespace aruco; struct Pose { int id; float x; float y; float z; float x_rotation; float y_rotation; float z_rotation; float w_rotation; }; /** * Adds vertix and edges in slam_solver and visualizer * @param new_keyframe_pose new keyframe that should be added * @param last_keyframe_pose the last keyframe added in graph, this is update this in this function * @param first_keyframe_pose the first keyframe * @param num_keyframes number of keyframes in graph, this is update in this function * @param slam_solver slam_solver reference * @param visualizer visualizer reference * @param is_loop_closure if the vertex added is a loop_closure as well */ void addVertixAndEdge( Eigen::Affine3f cam_pose, Eigen::Affine3f& last_keyframe_pose, Eigen::Affine3f aruco_pose, int& num_keyframes, SLAM_Solver& slam_solver, ReconstructionVisualizer& visualizer, bool is_loop_closure); /** * This program shows the use of camera pose estimation using optical flow visual odometry. * @param .yml config. file (from which index_file is used) */ int main(int argc, char** argv) { int num_keyframes = 0; bool slam_solver_started = false; float marker_size, aruco_max_distance; string camera_calibration_file, aruco_dic, index_file; EventLogger& logger = EventLogger::getInstance(); logger.setVerbosityLevel(EventLogger::L_ERROR); SLAM_Solver slam_solver; ReconstructionVisualizer visualizer; Intrinsics intr(0); OpticalFlowVisualOdometry vo(intr); MarkerFinder marker_finder; RGBDLoader loader; Mat frame, depth; Eigen::Affine3f last_keyframe_pose; Eigen::Affine3f first_keyframe_pose; // Slam solver will start when the marker is found for the first time if (argc != 2) { logger.print( EventLogger::L_ERROR, "[slam_solver_test.cpp] Usage: %s <path/to/config_file.yaml>\n", argv[0]); exit(0); } ConfigLoader param_loader(argv[1]); param_loader.checkAndGetString("index_file", index_file); param_loader.checkAndGetFloat("aruco_marker_size", marker_size); param_loader.checkAndGetFloat("aruco_max_distance", aruco_max_distance); param_loader.checkAndGetString("camera_calibration_file", camera_calibration_file); param_loader.checkAndGetString("aruco_dic", aruco_dic); marker_finder.markerParam(camera_calibration_file, marker_size, aruco_dic); loader.processFile(index_file); // Compute visual odometry on each image for (int i = 0; i < loader.num_images_; i++) { // Load RGB-D image loader.getNextImage(frame, depth); // If aruco is not found yet if (slam_solver_started == false) { marker_finder.detectMarkersPoses( frame, Eigen::Affine3f::Identity(), aruco_max_distance); for (size_t i = 0; i < marker_finder.markers_.size(); i++) { if (250 == marker_finder.markers_[i].id) { // If we found the mark for the first time, we will add the marker as the origin // of the system Then we add the first camera pose related to the marker pose. // Getting Camera Pose vo.pose_ = marker_finder.marker_poses_[i]; // Adding first pose to slam_solver and visualizer slam_solver.addVertexAndEdge(vo.pose_, num_keyframes); visualizer.addReferenceFrame(vo.pose_, to_string(num_keyframes)); num_keyframes++; // Increment the number of keyframes found // Set slam solver started to true since we found the marker for the first time slam_solver_started = true; first_keyframe_pose = vo.pose_; last_keyframe_pose = vo.pose_; } } continue; } // If we have already found the marker we start the keyframe process else { marker_finder.detectMarkersPoses(frame, vo.pose_, aruco_max_distance); for (size_t i = 0; i < marker_finder.markers_.size(); i++) { if (250 == marker_finder.markers_[i].id) { addVertixAndEdge( vo.pose_, last_keyframe_pose, marker_finder.marker_poses_[i], num_keyframes, slam_solver, visualizer, true); } } // Estimate current camera pose bool is_kf = vo.computeCameraPose(frame, depth); // View tracked points for (size_t k = 0; k < vo.tracker_.curr_pts_.size(); k++) { Point2i pt1 = vo.tracker_.prev_pts_[k]; Point2i pt2 = vo.tracker_.curr_pts_[k]; Scalar color; is_kf ? color = CV_RGB(255, 0, 0) : color = CV_RGB(0, 0, 255); circle(frame, pt1, 1, color, -1); circle(frame, pt2, 3, color, -1); line(frame, pt1, pt2, color); } visualizer.viewReferenceFrame(vo.pose_); visualizer.viewQuantizedPointCloud(vo.curr_dense_cloud_, 0.05, vo.pose_); visualizer.addQuantizedPointCloud(vo.curr_dense_cloud_, 0.05, vo.pose_); // If we found a keyframe we will added to slam solver and visualizer if (is_kf) { addVertixAndEdge( vo.pose_, last_keyframe_pose, Eigen::Affine3f::Identity(), num_keyframes, slam_solver, visualizer, false); } } visualizer.spinOnce(); imshow("Image view", frame); // imshow("Depth view", depth); char key = waitKey(1); if (key == 27 || key == 'q' || key == 'Q') { logger.print(EventLogger::L_INFO, "[slam_solver_test.cpp] Exiting\n", argv[0]); break; } } slam_solver.optimizeGraph(10); visualizer.addOptimizedEdges(slam_solver.odometry_edges_); visualizer.addOptimizedEdges(slam_solver.loop_edges_); visualizer.spin(); return 0; } void addVertixAndEdge( Eigen::Affine3f cam_pose, Eigen::Affine3f& last_keyframe_pose, Eigen::Affine3f aruco_pose, int& num_keyframes, SLAM_Solver& slam_solver, ReconstructionVisualizer& visualizer, bool is_loop_closure) { double x = pow(cam_pose(0, 3) - last_keyframe_pose(0, 3), 2); double y = pow(cam_pose(1, 3) - last_keyframe_pose(1, 3), 2); double z = pow(cam_pose(2, 3) - last_keyframe_pose(2, 3), 2); // We will only add a new keyframe if they have at least 5cm of distance between each other if (sqrt(x + y + z) >= 0.05) { // Adding keyframe in visualizer visualizer.addReferenceFrame(cam_pose, to_string(num_keyframes)); // Add the keyframe and creating an edge to the last vertex slam_solver.addVertexAndEdge(cam_pose, num_keyframes); visualizer.addEdge(slam_solver.odometry_edges_.back()); // If the keyframe is a loop closure we will create a loop closing edge if (is_loop_closure == true) { // Adding the loop closing edge that is an edge from this vertex to the initial // If we want to change the system coord from A to B -> A.inverse * B slam_solver.addLoopClosingEdge(cam_pose.inverse() * aruco_pose, num_keyframes); visualizer.addEdge(slam_solver.loop_edges_.back(), Eigen::Vector3f(1.0, 0.0, 0.0)); // Make a optimization in the graph from every 5 loop edges if (slam_solver.odometry_edges_.size() % 20 == 0) { // visualizer.removeEdges(slam_solver.odometry_edges_); // visualizer.removeEdges(slam_solver.loop_edges_); slam_solver.optimizeGraph(10); visualizer.addOptimizedEdges(slam_solver.odometry_edges_); visualizer.addOptimizedEdges(slam_solver.loop_edges_); } } num_keyframes++; // Increment the number of keyframes found last_keyframe_pose = cam_pose; // Updating the pose of last keyframe } }<|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "pow.h" #include "arith_uint256.h" #include "chain.h" #include "chainparams.h" #include "primitives/block.h" #include "uint256.h" #include "util.h" #include <math.h> unsigned int static KimotoGravityWell(const CBlockIndex* pindexLast, const Consensus::Params& params) { const CBlockIndex *BlockLastSolved = pindexLast; const CBlockIndex *BlockReading = pindexLast; uint64_t PastBlocksMass = 0; int64_t PastRateActualSeconds = 0; int64_t PastRateTargetSeconds = 0; double PastRateAdjustmentRatio = double(1); arith_uint256 PastDifficultyAverage; arith_uint256 PastDifficultyAveragePrev; double EventHorizonDeviation; double EventHorizonDeviationFast; double EventHorizonDeviationSlow; uint64_t pastSecondsMin = params.nPowTargetTimespan * 0.025; uint64_t pastSecondsMax = params.nPowTargetTimespan * 7; uint64_t PastBlocksMin = pastSecondsMin / params.nPowTargetSpacing; uint64_t PastBlocksMax = pastSecondsMax / params.nPowTargetSpacing; if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return UintToArith256(params.powLimit).GetCompact(); } for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (PastBlocksMax > 0 && i > PastBlocksMax) { break; } PastBlocksMass++; PastDifficultyAverage.SetCompact(BlockReading->nBits); if (i > 1) { // handle negative arith_uint256 if(PastDifficultyAverage >= PastDifficultyAveragePrev) PastDifficultyAverage = ((PastDifficultyAverage - PastDifficultyAveragePrev) / i) + PastDifficultyAveragePrev; else PastDifficultyAverage = PastDifficultyAveragePrev - ((PastDifficultyAveragePrev - PastDifficultyAverage) / i); } PastDifficultyAveragePrev = PastDifficultyAverage; PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime(); PastRateTargetSeconds = params.nPowTargetSpacing * PastBlocksMass; PastRateAdjustmentRatio = double(1); if (PastRateActualSeconds < 0) { PastRateActualSeconds = 0; } if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) { PastRateAdjustmentRatio = double(PastRateTargetSeconds) / double(PastRateActualSeconds); } EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)/double(28.2)), -1.228)); EventHorizonDeviationFast = EventHorizonDeviation; EventHorizonDeviationSlow = 1 / EventHorizonDeviation; if (PastBlocksMass >= PastBlocksMin) { if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast)) { assert(BlockReading); break; } } if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } arith_uint256 bnNew(PastDifficultyAverage); if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) { bnNew *= PastRateActualSeconds; bnNew /= PastRateTargetSeconds; } if (bnNew > UintToArith256(params.powLimit)) { bnNew = UintToArith256(params.powLimit); } return bnNew.GetCompact(); } unsigned int static DarkGravityWave(const CBlockIndex* pindexLast, const Consensus::Params& params) { /* current difficulty formula, innova - DarkGravity v3, written by Evan Duffield - [email protected] */ const CBlockIndex *BlockLastSolved = pindexLast; const CBlockIndex *BlockReading = pindexLast; int64_t nActualTimespan = 0; int64_t LastBlockTime = 0; int64_t PastBlocksMin = 24; int64_t PastBlocksMax = 24; int64_t CountBlocks = 0; arith_uint256 PastDifficultyAverage; arith_uint256 PastDifficultyAveragePrev; if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || BlockLastSolved->nHeight < PastBlocksMin) { return UintToArith256(params.powLimit).GetCompact(); } for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (PastBlocksMax > 0 && i > PastBlocksMax) { break; } CountBlocks++; if(CountBlocks <= PastBlocksMin) { if (CountBlocks == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); } else { PastDifficultyAverage = ((PastDifficultyAveragePrev * CountBlocks) + (arith_uint256().SetCompact(BlockReading->nBits))) / (CountBlocks + 1); } PastDifficultyAveragePrev = PastDifficultyAverage; } if(LastBlockTime > 0){ int64_t Diff = (LastBlockTime - BlockReading->GetBlockTime()); nActualTimespan += Diff; } LastBlockTime = BlockReading->GetBlockTime(); if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } arith_uint256 bnNew(PastDifficultyAverage); int64_t _nTargetTimespan = CountBlocks * params.nPowTargetSpacing; if (nActualTimespan < _nTargetTimespan/3) nActualTimespan = _nTargetTimespan/3; if (nActualTimespan > _nTargetTimespan*3) nActualTimespan = _nTargetTimespan*3; // Retarget bnNew *= nActualTimespan; bnNew /= _nTargetTimespan; if (bnNew > UintToArith256(params.powLimit)){ bnNew = UintToArith256(params.powLimit); } return bnNew.GetCompact(); } unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) { unsigned int retarget = DIFF_DGW; // mainnet/regtest share a configuration if (Params().NetworkIDString() == CBaseChainParams::MAIN || Params().NetworkIDString() == CBaseChainParams::REGTEST) { if (pindexLast->nHeight + 1 >= 15200) retarget = DIFF_DGW; else retarget = DIFF_BTC; // testnet -- we want a lot of coins in existance early on } else { if (pindexLast->nHeight + 1 >= 3000) retarget = DIFF_DGW; else retarget = DIFF_BTC; } // Default Bitcoin style retargeting if (retarget == DIFF_BTC) { unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact(); // Genesis block if (pindexLast == NULL) return nProofOfWorkLimit; // Only change once per interval if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0) { if (params.fPowAllowMinDifficultyBlocks) { // Special difficulty rule for testnet: // If the new block's timestamp is more than 2* 2.5 minutes // then allow mining of a min-difficulty block. if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2) return nProofOfWorkLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit) pindex = pindex->pprev; return pindex->nBits; } } return pindexLast->nBits; } // Go back by what we want to be 1 day worth of blocks int nHeightFirst = pindexLast->nHeight - (params.DifficultyAdjustmentInterval()-1); assert(nHeightFirst >= 0); const CBlockIndex* pindexFirst = pindexLast->GetAncestor(nHeightFirst); assert(pindexFirst); return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params); } // Retarget using Kimoto Gravity Wave else if (retarget == DIFF_KGW) { return KimotoGravityWell(pindexLast, params); } // Retarget using Dark Gravity Wave 3 else if (retarget == DIFF_DGW) { return DarkGravityWave(pindexLast, params); } return DarkGravityWave(pindexLast, params); } // for DIFF_BTC only! unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params) { if (params.fPowNoRetargeting) return pindexLast->nBits; // Limit adjustment step int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime; LogPrintf(" nActualTimespan = %d before bounds\n", nActualTimespan); if (nActualTimespan < params.nPowTargetTimespan/4) nActualTimespan = params.nPowTargetTimespan/4; if (nActualTimespan > params.nPowTargetTimespan*4) nActualTimespan = params.nPowTargetTimespan*4; // Retarget const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); arith_uint256 bnNew; arith_uint256 bnOld; bnNew.SetCompact(pindexLast->nBits); bnOld = bnNew; bnNew *= nActualTimespan; bnNew /= params.nPowTargetTimespan; if (bnNew > bnPowLimit) bnNew = bnPowLimit; /// debug print LogPrintf("GetNextWorkRequired RETARGET\n"); LogPrintf("params.nPowTargetTimespan = %d nActualTimespan = %d\n", params.nPowTargetTimespan, nActualTimespan); LogPrintf("Before: %08x %s\n", pindexLast->nBits, bnOld.ToString()); LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString()); return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params) { bool fNegative; bool fOverflow; arith_uint256 bnTarget; bnTarget.SetCompact(nBits, &fNegative, &fOverflow); // Check range if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) return error("CheckProofOfWork(): nBits below minimum work"); // Check proof of work matches claimed amount if (UintToArith256(hash) > bnTarget) return error("CheckProofOfWork(): hash doesn't match nBits"); return true; } arith_uint256 GetBlockProof(const CBlockIndex& block) { arith_uint256 bnTarget; bool fNegative; bool fOverflow; bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow); if (fNegative || fOverflow || bnTarget == 0) return 0; // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256 // as it's too large for a arith_uint256. However, as 2**256 is at least as large // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1, // or ~bnTarget / (nTarget+1) + 1. return (~bnTarget / (bnTarget + 1)) + 1; } int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params) { arith_uint256 r; int sign = 1; if (to.nChainWork > from.nChainWork) { r = to.nChainWork - from.nChainWork; } else { r = from.nChainWork - to.nChainWork; sign = -1; } r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip); if (r.bits() > 63) { return sign * std::numeric_limits<int64_t>::max(); } return sign * r.GetLow64(); } <commit_msg>retargeting fixed<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "pow.h" #include "arith_uint256.h" #include "chain.h" #include "chainparams.h" #include "primitives/block.h" #include "uint256.h" #include "util.h" #include <math.h> unsigned int static KimotoGravityWell(const CBlockIndex* pindexLast, const Consensus::Params& params) { const CBlockIndex *BlockLastSolved = pindexLast; const CBlockIndex *BlockReading = pindexLast; uint64_t PastBlocksMass = 0; int64_t PastRateActualSeconds = 0; int64_t PastRateTargetSeconds = 0; double PastRateAdjustmentRatio = double(1); arith_uint256 PastDifficultyAverage; arith_uint256 PastDifficultyAveragePrev; double EventHorizonDeviation; double EventHorizonDeviationFast; double EventHorizonDeviationSlow; uint64_t pastSecondsMin = params.nPowTargetTimespan * 0.025; uint64_t pastSecondsMax = params.nPowTargetTimespan * 7; uint64_t PastBlocksMin = pastSecondsMin / params.nPowTargetSpacing; uint64_t PastBlocksMax = pastSecondsMax / params.nPowTargetSpacing; if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return UintToArith256(params.powLimit).GetCompact(); } for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (PastBlocksMax > 0 && i > PastBlocksMax) { break; } PastBlocksMass++; PastDifficultyAverage.SetCompact(BlockReading->nBits); if (i > 1) { // handle negative arith_uint256 if(PastDifficultyAverage >= PastDifficultyAveragePrev) PastDifficultyAverage = ((PastDifficultyAverage - PastDifficultyAveragePrev) / i) + PastDifficultyAveragePrev; else PastDifficultyAverage = PastDifficultyAveragePrev - ((PastDifficultyAveragePrev - PastDifficultyAverage) / i); } PastDifficultyAveragePrev = PastDifficultyAverage; PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime(); PastRateTargetSeconds = params.nPowTargetSpacing * PastBlocksMass; PastRateAdjustmentRatio = double(1); if (PastRateActualSeconds < 0) { PastRateActualSeconds = 0; } if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) { PastRateAdjustmentRatio = double(PastRateTargetSeconds) / double(PastRateActualSeconds); } EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)/double(28.2)), -1.228)); EventHorizonDeviationFast = EventHorizonDeviation; EventHorizonDeviationSlow = 1 / EventHorizonDeviation; if (PastBlocksMass >= PastBlocksMin) { if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast)) { assert(BlockReading); break; } } if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } arith_uint256 bnNew(PastDifficultyAverage); if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) { bnNew *= PastRateActualSeconds; bnNew /= PastRateTargetSeconds; } if (bnNew > UintToArith256(params.powLimit)) { bnNew = UintToArith256(params.powLimit); } return bnNew.GetCompact(); } unsigned int static DarkGravityWave(const CBlockIndex* pindexLast, const Consensus::Params& params) { /* current difficulty formula, innova - DarkGravity v3, written by Evan Duffield - [email protected] */ const CBlockIndex *BlockLastSolved = pindexLast; const CBlockIndex *BlockReading = pindexLast; int64_t nActualTimespan = 0; int64_t LastBlockTime = 0; int64_t PastBlocksMin = 24; int64_t PastBlocksMax = 24; int64_t CountBlocks = 0; arith_uint256 PastDifficultyAverage; arith_uint256 PastDifficultyAveragePrev; if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || BlockLastSolved->nHeight < PastBlocksMin) { return UintToArith256(params.powLimit).GetCompact(); } for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (PastBlocksMax > 0 && i > PastBlocksMax) { break; } CountBlocks++; if(CountBlocks <= PastBlocksMin) { if (CountBlocks == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); } else { PastDifficultyAverage = ((PastDifficultyAveragePrev * CountBlocks) + (arith_uint256().SetCompact(BlockReading->nBits))) / (CountBlocks + 1); } PastDifficultyAveragePrev = PastDifficultyAverage; } if(LastBlockTime > 0){ int64_t Diff = (LastBlockTime - BlockReading->GetBlockTime()); nActualTimespan += Diff; } LastBlockTime = BlockReading->GetBlockTime(); if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } arith_uint256 bnNew(PastDifficultyAverage); int64_t _nTargetTimespan = CountBlocks * params.nPowTargetSpacing; if (nActualTimespan < _nTargetTimespan/3) nActualTimespan = _nTargetTimespan/3; if (nActualTimespan > _nTargetTimespan*3) nActualTimespan = _nTargetTimespan*3; // Retarget bnNew *= nActualTimespan; bnNew /= _nTargetTimespan; if (bnNew > UintToArith256(params.powLimit)){ bnNew = UintToArith256(params.powLimit); } return bnNew.GetCompact(); } unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) { unsigned int retarget = DIFF_DGW; // mainnet/regtest share a configuration if (Params().NetworkIDString() == CBaseChainParams::MAIN || Params().NetworkIDString() == CBaseChainParams::REGTEST) { if (pindexLast->nHeight + 1 >= 2075) retarget = DIFF_DGW; else retarget = DIFF_BTC; // testnet -- we want a lot of coins in existance early on } else { if (pindexLast->nHeight + 1 >= 3000) retarget = DIFF_DGW; else retarget = DIFF_BTC; } // Default Bitcoin style retargeting if (retarget == DIFF_BTC) { unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact(); // Genesis block if (pindexLast == NULL) return nProofOfWorkLimit; // Only change once per interval if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0) { if (params.fPowAllowMinDifficultyBlocks) { // Special difficulty rule for testnet: // If the new block's timestamp is more than 2* 2.5 minutes // then allow mining of a min-difficulty block. if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2) return nProofOfWorkLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit) pindex = pindex->pprev; return pindex->nBits; } } return pindexLast->nBits; } // Go back by what we want to be 1 day worth of blocks int nHeightFirst = pindexLast->nHeight - (params.DifficultyAdjustmentInterval()-1); assert(nHeightFirst >= 0); const CBlockIndex* pindexFirst = pindexLast->GetAncestor(nHeightFirst); assert(pindexFirst); return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params); } // Retarget using Kimoto Gravity Wave else if (retarget == DIFF_KGW) { return KimotoGravityWell(pindexLast, params); } // Retarget using Dark Gravity Wave 3 else if (retarget == DIFF_DGW) { return DarkGravityWave(pindexLast, params); } return DarkGravityWave(pindexLast, params); } // for DIFF_BTC only! unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params) { if (params.fPowNoRetargeting) return pindexLast->nBits; // Limit adjustment step int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime; LogPrintf(" nActualTimespan = %d before bounds\n", nActualTimespan); if (nActualTimespan < params.nPowTargetTimespan/4) nActualTimespan = params.nPowTargetTimespan/4; if (nActualTimespan > params.nPowTargetTimespan*4) nActualTimespan = params.nPowTargetTimespan*4; // Retarget const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); arith_uint256 bnNew; arith_uint256 bnOld; bnNew.SetCompact(pindexLast->nBits); bnOld = bnNew; bnNew *= nActualTimespan; bnNew /= params.nPowTargetTimespan; if (bnNew > bnPowLimit) bnNew = bnPowLimit; /// debug print LogPrintf("GetNextWorkRequired RETARGET\n"); LogPrintf("params.nPowTargetTimespan = %d nActualTimespan = %d\n", params.nPowTargetTimespan, nActualTimespan); LogPrintf("Before: %08x %s\n", pindexLast->nBits, bnOld.ToString()); LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString()); return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params) { bool fNegative; bool fOverflow; arith_uint256 bnTarget; bnTarget.SetCompact(nBits, &fNegative, &fOverflow); // Check range if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) return error("CheckProofOfWork(): nBits below minimum work"); // Check proof of work matches claimed amount if (UintToArith256(hash) > bnTarget) return error("CheckProofOfWork(): hash doesn't match nBits"); return true; } arith_uint256 GetBlockProof(const CBlockIndex& block) { arith_uint256 bnTarget; bool fNegative; bool fOverflow; bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow); if (fNegative || fOverflow || bnTarget == 0) return 0; // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256 // as it's too large for a arith_uint256. However, as 2**256 is at least as large // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1, // or ~bnTarget / (nTarget+1) + 1. return (~bnTarget / (bnTarget + 1)) + 1; } int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params) { arith_uint256 r; int sign = 1; if (to.nChainWork > from.nChainWork) { r = to.nChainWork - from.nChainWork; } else { r = from.nChainWork - to.nChainWork; sign = -1; } r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip); if (r.bits() > 63) { return sign * std::numeric_limits<int64_t>::max(); } return sign * r.GetLow64(); } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "pow.h" #include "arith_uint256.h" #include "chain.h" #include "chainparams.h" #include "primitives/block.h" #include "uint256.h" #include "util.h" #include "bignum.h" unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, int algo, const Consensus::Params& params) { unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact(); // Genesis block if (pindexLast == NULL) return nProofOfWorkLimit; if (params.fPowAllowMinDifficultyBlocks) { // Special difficulty rule for testnet: // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. // TODO Myriadcoin: enable this at the next hard fork for testnet /* if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2) return nProofOfWorkLimit; */ } // find previous block with same algo const CBlockIndex* pindexPrev = GetLastBlockIndexForAlgo(pindexLast, algo); const CBlockIndex* pindexFirst = NULL; if( (pindexLast->nHeight >= params.nBlockTimeWarpPreventStart1) && (pindexLast->nHeight < params.nBlockTimeWarpPreventStart2) ) { // find first block in averaging interval // Go back by what we want to be nAveragingInterval blocks pindexFirst = pindexPrev; for (int i = 0; pindexFirst && i < params.nAveragingInterval - 1; i++) { pindexFirst = pindexFirst->pprev; pindexFirst = GetLastBlockIndexForAlgo(pindexFirst, algo); } if (pindexFirst == NULL) return nProofOfWorkLimit; // not nAveragingInterval blocks of this algo available // check block before first block for time warp const CBlockIndex* pindexFirstPrev = pindexFirst->pprev; if (pindexFirstPrev == NULL) return nProofOfWorkLimit; pindexFirstPrev = GetLastBlockIndexForAlgo(pindexFirstPrev, algo); if (pindexFirstPrev == NULL) return nProofOfWorkLimit; // take previous block if block times are out of order if (pindexFirstPrev->GetBlockTime() > pindexFirst->GetBlockTime()) { LogPrintf(" First blocks out of order times, swapping: %d %d\n", pindexFirstPrev->GetBlockTime(), pindexFirst->GetBlockTime()); pindexFirst = pindexFirstPrev; } } else if ( (pindexLast->nHeight >= params.nBlockTimeWarpPreventStart2) && (pindexLast->nHeight < params.nBlockTimeWarpPreventStart3) ) { // find first block in averaging interval // Go back by what we want to be nAveragingInterval blocks pindexFirst = pindexPrev; for (int i = 0; pindexFirst && i < params.nAveragingInterval - 1; i++) { pindexFirst = pindexFirst->pprev; pindexFirst = GetLastBlockIndexForAlgo(pindexFirst, algo); } if (pindexFirst == NULL) return nProofOfWorkLimit; // not nAveragingInterval blocks of this algo available const CBlockIndex* pindexFirstPrev; for ( ;; ) { // check blocks before first block for time warp pindexFirstPrev = pindexFirst->pprev; if (pindexFirstPrev == NULL) return nProofOfWorkLimit; pindexFirstPrev = GetLastBlockIndexForAlgo(pindexFirstPrev, algo); if (pindexFirstPrev == NULL) return nProofOfWorkLimit; // take previous block if block times are out of order if (pindexFirstPrev->GetBlockTime() > pindexFirst->GetBlockTime()) { LogPrintf(" First blocks out of order times, swapping: %d %d\n", pindexFirstPrev->GetBlockTime(), pindexFirst->GetBlockTime()); pindexFirst = pindexFirstPrev; } else break; } } else { // find first block in averaging interval // Go back by what we want to be nAveragingInterval blocks pindexFirst = pindexPrev; for (int i = 0; pindexFirst && i < params.nAveragingInterval - 1; i++) { pindexFirst = pindexFirst->pprev; pindexFirst = GetLastBlockIndexForAlgo(pindexFirst, algo); if (pindexFirst == NULL) { if(fDebug) { LogPrintf("pindexFirst is null. returning nProofOfWorkLimit\n"); } return nProofOfWorkLimit; } } } int64_t nActualTimespan; if (pindexLast->nHeight >= params.nBlockTimeWarpPreventStart3) { nActualTimespan = pindexPrev->GetMedianTimePast() - pindexFirst->GetMedianTimePast(); if(fDebug) { LogPrintf(" nActualTimespan = %d before bounds %d %d\n", nActualTimespan, pindexPrev->GetMedianTimePast(), pindexFirst->GetMedianTimePast()); } } else { nActualTimespan = pindexPrev->GetBlockTime() - pindexFirst->GetBlockTime(); if(fDebug) { LogPrintf(" nActualTimespan = %d before bounds %d %d\n", nActualTimespan, pindexPrev->GetBlockTime(), pindexFirst->GetBlockTime()); } } // Time warp mitigation: Don't adjust difficulty if time is negative if ( (pindexLast->nHeight >= params.nBlockTimeWarpPreventStart1) && (pindexLast->nHeight < params.nBlockTimeWarpPreventStart2) ) { if (nActualTimespan < 0) { if(fDebug) { LogPrintf(" nActualTimespan negative %d\n", nActualTimespan); LogPrintf(" Keeping: %08x \n", pindexPrev->nBits); } return pindexPrev->nBits; } } if (pindexLast->nHeight >= params.Phase2Timespan_Start) { return CalculateNextWorkRequiredV2(pindexPrev, pindexFirst, params, algo, nActualTimespan); } else { return CalculateNextWorkRequiredV1(pindexPrev, pindexFirst, params, algo, nActualTimespan, pindexLast->nHeight); } } unsigned int CalculateNextWorkRequiredV1(const CBlockIndex* pindexPrev, const CBlockIndex* pindexFirst, const Consensus::Params& params, int algo, int64_t nActualTimespan, int nHeight) { if (params.fPowNoRetargeting) return pindexPrev->nBits; const arith_uint256 nProofOfWorkLimit = UintToArith256(params.powLimit); int64_t nTargetSpacingPerAlgo = params.nPowTargetSpacingV1 * NUM_ALGOS; // 30 * 5 = 150s per algo int64_t nAveragingTargetTimespan = params.nAveragingInterval * nTargetSpacingPerAlgo; // 10 * 150 = 1500s, 25 minutes int64_t nMinActualTimespanV1 = nAveragingTargetTimespan * (100 - params.nMaxAdjustUpV1) / 100; int64_t nMinActualTimespanV2 = nAveragingTargetTimespan * (100 - params.nMaxAdjustUpV2) / 100; int64_t nMaxActualTimespan = nAveragingTargetTimespan * (100 + params.nMaxAdjustDown) / 100; int64_t nMinActualTimespan; if (nHeight >= params.nBlockDiffAdjustV2) { nMinActualTimespan = nMinActualTimespanV2; } else { nMinActualTimespan = nMinActualTimespanV1; } if (nActualTimespan < nMinActualTimespan) nActualTimespan = nMinActualTimespan; if (nActualTimespan > nMaxActualTimespan) nActualTimespan = nMaxActualTimespan; if(fDebug) { LogPrintf(" nActualTimespan = %d after bounds %d %d\n", nActualTimespan, nMinActualTimespan, nMaxActualTimespan); } // Retarget arith_uint256 bnNew; arith_uint256 bnOld; bnNew.SetCompact(pindexPrev->nBits); bnOld = bnNew; bnNew *= nActualTimespan; bnNew /= nAveragingTargetTimespan; if (bnNew > nProofOfWorkLimit) bnNew = nProofOfWorkLimit; /// debug print if(fDebug) { LogPrintf("CalculateNextWorkRequiredV1(Algo=%d): RETARGET\n", algo); LogPrintf("CalculateNextWorkRequiredV1(Algo=%d): nTargetTimespan = %d nActualTimespan = %d\n", algo, nAveragingTargetTimespan, nActualTimespan); LogPrintf("CalculateNextWorkRequiredV1(Algo=%d): Before: %08x %s\n", algo, pindexPrev->nBits, bnOld.ToString()); LogPrintf("CalculateNextWorkRequiredV1(Algo=%d): After: %08x %s\n", algo, bnNew.GetCompact(), bnNew.ToString()); } return bnNew.GetCompact(); } unsigned int CalculateNextWorkRequiredV2(const CBlockIndex* pindexPrev, const CBlockIndex* pindexFirst, const Consensus::Params& params, int algo, int64_t nActualTimespan) { if (params.fPowNoRetargeting) return pindexPrev->nBits; const arith_uint256 nProofOfWorkLimit = UintToArith256(params.powLimit); int64_t nTargetSpacingPerAlgo = params.nPowTargetSpacingV2 * NUM_ALGOS; // 60 * 5 = 300s per algo int64_t nAveragingTargetTimespan = params.nAveragingInterval * nTargetSpacingPerAlgo; // 10 * 300 = 3000s, 50 minutes int64_t nMinActualTimespan = nAveragingTargetTimespan * (100 - params.nMaxAdjustUpV2) / 100; int64_t nMaxActualTimespan = nAveragingTargetTimespan * (100 + params.nMaxAdjustDown) / 100; if (nActualTimespan < nMinActualTimespan) nActualTimespan = nMinActualTimespan; if (nActualTimespan > nMaxActualTimespan) nActualTimespan = nMaxActualTimespan; if(fDebug) { LogPrintf(" nActualTimespan = %d after bounds %d %d\n", nActualTimespan, nMinActualTimespan, nMaxActualTimespan); } arith_uint256 bnNew; arith_uint256 bnOld; bnNew.SetCompact(pindexPrev->nBits); bnOld = bnNew; bnNew *= nActualTimespan; bnNew /= nAveragingTargetTimespan; if (bnNew > nProofOfWorkLimit) bnNew = nProofOfWorkLimit; /// debug print if(fDebug) { LogPrintf("CalculateNextWorkRequiredV2(Algo=%d): RETARGET\n", algo); LogPrintf("CalculateNextWorkRequiredV2(Algo=%d): nTargetTimespan = %d nActualTimespan = %d\n", algo, nAveragingTargetTimespan, nActualTimespan); LogPrintf("CalculateNextWorkRequiredV2(Algo=%d): Before: %08x %s\n", algo, pindexPrev->nBits, bnOld.ToString()); LogPrintf("CalculateNextWorkRequiredV2(Algo=%d): After: %08x %s\n", algo, bnNew.GetCompact(), bnNew.ToString()); } return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, int algo, unsigned int nBits, const Consensus::Params& params) { bool fNegative; bool fOverflow; arith_uint256 bnTarget; bnTarget.SetCompact(nBits, &fNegative, &fOverflow); // Check range if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) return false; // Check proof of work matches claimed amount if (UintToArith256(hash) > bnTarget) return false; return true; } <commit_msg>check for genesis again after previous algo<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "pow.h" #include "arith_uint256.h" #include "chain.h" #include "chainparams.h" #include "primitives/block.h" #include "uint256.h" #include "util.h" #include "bignum.h" unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, int algo, const Consensus::Params& params) { unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact(); // Genesis block if (pindexLast == NULL) return nProofOfWorkLimit; if (params.fPowAllowMinDifficultyBlocks) { // Special difficulty rule for testnet: // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. // TODO Myriadcoin: enable this at the next hard fork for testnet /* if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2) return nProofOfWorkLimit; */ } // find previous block with same algo const CBlockIndex* pindexPrev = GetLastBlockIndexForAlgo(pindexLast, algo); // Genesis block check again if (pindexPrev == NULL) return nProofOfWorkLimit; const CBlockIndex* pindexFirst = NULL; if( (pindexLast->nHeight >= params.nBlockTimeWarpPreventStart1) && (pindexLast->nHeight < params.nBlockTimeWarpPreventStart2) ) { // find first block in averaging interval // Go back by what we want to be nAveragingInterval blocks pindexFirst = pindexPrev; for (int i = 0; pindexFirst && i < params.nAveragingInterval - 1; i++) { pindexFirst = pindexFirst->pprev; pindexFirst = GetLastBlockIndexForAlgo(pindexFirst, algo); } if (pindexFirst == NULL) return nProofOfWorkLimit; // not nAveragingInterval blocks of this algo available // check block before first block for time warp const CBlockIndex* pindexFirstPrev = pindexFirst->pprev; if (pindexFirstPrev == NULL) return nProofOfWorkLimit; pindexFirstPrev = GetLastBlockIndexForAlgo(pindexFirstPrev, algo); if (pindexFirstPrev == NULL) return nProofOfWorkLimit; // take previous block if block times are out of order if (pindexFirstPrev->GetBlockTime() > pindexFirst->GetBlockTime()) { LogPrintf(" First blocks out of order times, swapping: %d %d\n", pindexFirstPrev->GetBlockTime(), pindexFirst->GetBlockTime()); pindexFirst = pindexFirstPrev; } } else if ( (pindexLast->nHeight >= params.nBlockTimeWarpPreventStart2) && (pindexLast->nHeight < params.nBlockTimeWarpPreventStart3) ) { // find first block in averaging interval // Go back by what we want to be nAveragingInterval blocks pindexFirst = pindexPrev; for (int i = 0; pindexFirst && i < params.nAveragingInterval - 1; i++) { pindexFirst = pindexFirst->pprev; pindexFirst = GetLastBlockIndexForAlgo(pindexFirst, algo); } if (pindexFirst == NULL) return nProofOfWorkLimit; // not nAveragingInterval blocks of this algo available const CBlockIndex* pindexFirstPrev; for ( ;; ) { // check blocks before first block for time warp pindexFirstPrev = pindexFirst->pprev; if (pindexFirstPrev == NULL) return nProofOfWorkLimit; pindexFirstPrev = GetLastBlockIndexForAlgo(pindexFirstPrev, algo); if (pindexFirstPrev == NULL) return nProofOfWorkLimit; // take previous block if block times are out of order if (pindexFirstPrev->GetBlockTime() > pindexFirst->GetBlockTime()) { LogPrintf(" First blocks out of order times, swapping: %d %d\n", pindexFirstPrev->GetBlockTime(), pindexFirst->GetBlockTime()); pindexFirst = pindexFirstPrev; } else break; } } else { // find first block in averaging interval // Go back by what we want to be nAveragingInterval blocks pindexFirst = pindexPrev; for (int i = 0; pindexFirst && i < params.nAveragingInterval - 1; i++) { pindexFirst = pindexFirst->pprev; pindexFirst = GetLastBlockIndexForAlgo(pindexFirst, algo); if (pindexFirst == NULL) { if(fDebug) { LogPrintf("pindexFirst is null. returning nProofOfWorkLimit\n"); } return nProofOfWorkLimit; } } } int64_t nActualTimespan; if (pindexLast->nHeight >= params.nBlockTimeWarpPreventStart3) { nActualTimespan = pindexPrev->GetMedianTimePast() - pindexFirst->GetMedianTimePast(); if(fDebug) { LogPrintf(" nActualTimespan = %d before bounds %d %d\n", nActualTimespan, pindexPrev->GetMedianTimePast(), pindexFirst->GetMedianTimePast()); } } else { nActualTimespan = pindexPrev->GetBlockTime() - pindexFirst->GetBlockTime(); if(fDebug) { LogPrintf(" nActualTimespan = %d before bounds %d %d\n", nActualTimespan, pindexPrev->GetBlockTime(), pindexFirst->GetBlockTime()); } } // Time warp mitigation: Don't adjust difficulty if time is negative if ( (pindexLast->nHeight >= params.nBlockTimeWarpPreventStart1) && (pindexLast->nHeight < params.nBlockTimeWarpPreventStart2) ) { if (nActualTimespan < 0) { if(fDebug) { LogPrintf(" nActualTimespan negative %d\n", nActualTimespan); LogPrintf(" Keeping: %08x \n", pindexPrev->nBits); } return pindexPrev->nBits; } } if (pindexLast->nHeight >= params.Phase2Timespan_Start) { return CalculateNextWorkRequiredV2(pindexPrev, pindexFirst, params, algo, nActualTimespan); } else { return CalculateNextWorkRequiredV1(pindexPrev, pindexFirst, params, algo, nActualTimespan, pindexLast->nHeight); } } unsigned int CalculateNextWorkRequiredV1(const CBlockIndex* pindexPrev, const CBlockIndex* pindexFirst, const Consensus::Params& params, int algo, int64_t nActualTimespan, int nHeight) { if (params.fPowNoRetargeting) return pindexPrev->nBits; const arith_uint256 nProofOfWorkLimit = UintToArith256(params.powLimit); int64_t nTargetSpacingPerAlgo = params.nPowTargetSpacingV1 * NUM_ALGOS; // 30 * 5 = 150s per algo int64_t nAveragingTargetTimespan = params.nAveragingInterval * nTargetSpacingPerAlgo; // 10 * 150 = 1500s, 25 minutes int64_t nMinActualTimespanV1 = nAveragingTargetTimespan * (100 - params.nMaxAdjustUpV1) / 100; int64_t nMinActualTimespanV2 = nAveragingTargetTimespan * (100 - params.nMaxAdjustUpV2) / 100; int64_t nMaxActualTimespan = nAveragingTargetTimespan * (100 + params.nMaxAdjustDown) / 100; int64_t nMinActualTimespan; if (nHeight >= params.nBlockDiffAdjustV2) { nMinActualTimespan = nMinActualTimespanV2; } else { nMinActualTimespan = nMinActualTimespanV1; } if (nActualTimespan < nMinActualTimespan) nActualTimespan = nMinActualTimespan; if (nActualTimespan > nMaxActualTimespan) nActualTimespan = nMaxActualTimespan; if(fDebug) { LogPrintf(" nActualTimespan = %d after bounds %d %d\n", nActualTimespan, nMinActualTimespan, nMaxActualTimespan); } // Retarget arith_uint256 bnNew; arith_uint256 bnOld; bnNew.SetCompact(pindexPrev->nBits); bnOld = bnNew; bnNew *= nActualTimespan; bnNew /= nAveragingTargetTimespan; if (bnNew > nProofOfWorkLimit) bnNew = nProofOfWorkLimit; /// debug print if(fDebug) { LogPrintf("CalculateNextWorkRequiredV1(Algo=%d): RETARGET\n", algo); LogPrintf("CalculateNextWorkRequiredV1(Algo=%d): nTargetTimespan = %d nActualTimespan = %d\n", algo, nAveragingTargetTimespan, nActualTimespan); LogPrintf("CalculateNextWorkRequiredV1(Algo=%d): Before: %08x %s\n", algo, pindexPrev->nBits, bnOld.ToString()); LogPrintf("CalculateNextWorkRequiredV1(Algo=%d): After: %08x %s\n", algo, bnNew.GetCompact(), bnNew.ToString()); } return bnNew.GetCompact(); } unsigned int CalculateNextWorkRequiredV2(const CBlockIndex* pindexPrev, const CBlockIndex* pindexFirst, const Consensus::Params& params, int algo, int64_t nActualTimespan) { if (params.fPowNoRetargeting) return pindexPrev->nBits; const arith_uint256 nProofOfWorkLimit = UintToArith256(params.powLimit); int64_t nTargetSpacingPerAlgo = params.nPowTargetSpacingV2 * NUM_ALGOS; // 60 * 5 = 300s per algo int64_t nAveragingTargetTimespan = params.nAveragingInterval * nTargetSpacingPerAlgo; // 10 * 300 = 3000s, 50 minutes int64_t nMinActualTimespan = nAveragingTargetTimespan * (100 - params.nMaxAdjustUpV2) / 100; int64_t nMaxActualTimespan = nAveragingTargetTimespan * (100 + params.nMaxAdjustDown) / 100; if (nActualTimespan < nMinActualTimespan) nActualTimespan = nMinActualTimespan; if (nActualTimespan > nMaxActualTimespan) nActualTimespan = nMaxActualTimespan; if(fDebug) { LogPrintf(" nActualTimespan = %d after bounds %d %d\n", nActualTimespan, nMinActualTimespan, nMaxActualTimespan); } arith_uint256 bnNew; arith_uint256 bnOld; bnNew.SetCompact(pindexPrev->nBits); bnOld = bnNew; bnNew *= nActualTimespan; bnNew /= nAveragingTargetTimespan; if (bnNew > nProofOfWorkLimit) bnNew = nProofOfWorkLimit; /// debug print if(fDebug) { LogPrintf("CalculateNextWorkRequiredV2(Algo=%d): RETARGET\n", algo); LogPrintf("CalculateNextWorkRequiredV2(Algo=%d): nTargetTimespan = %d nActualTimespan = %d\n", algo, nAveragingTargetTimespan, nActualTimespan); LogPrintf("CalculateNextWorkRequiredV2(Algo=%d): Before: %08x %s\n", algo, pindexPrev->nBits, bnOld.ToString()); LogPrintf("CalculateNextWorkRequiredV2(Algo=%d): After: %08x %s\n", algo, bnNew.GetCompact(), bnNew.ToString()); } return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, int algo, unsigned int nBits, const Consensus::Params& params) { bool fNegative; bool fOverflow; arith_uint256 bnTarget; bnTarget.SetCompact(nBits, &fNegative, &fOverflow); // Check range if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) return false; // Check proof of work matches claimed amount if (UintToArith256(hash) > bnTarget) return false; return true; } <|endoftext|>
<commit_before>#pragma once #include <bts/blockchain/types.hpp> namespace bts { namespace blockchain { static std::unordered_map<uint32_t, bts::blockchain::block_id_type> CHECKPOINT_BLOCKS { { 1, bts::blockchain::block_id_type( "8abcfb93c52f999e3ef5288c4f837f4f15af5521" ) }, { 100000, bts::blockchain::block_id_type( "96f98d49722848a6a47ad04aece8b9f93c9e9c23" ) }, { 200000, bts::blockchain::block_id_type( "222ddc49db592103c51ad22cdc4140185ef564d9" ) }, { 300000, bts::blockchain::block_id_type( "0d1d0b8f7f1f4590f8e083edc03869383ed74e3e" ) }, { 400000, bts::blockchain::block_id_type( "053d398b6597d5c61365afd100d87b824bf49f65" ) }, { 500000, bts::blockchain::block_id_type( "f02910a7115fb826984ce3a432cb371d5d7a99b8" ) }, { 600000, bts::blockchain::block_id_type( "f278db8722235343c9db9f077fe67c54a5f25f3b" ) }, { 700000, bts::blockchain::block_id_type( "f120ff9b159661b9ac084a0a69c58dcbd79cbb49" ) }, { 800000, bts::blockchain::block_id_type( "0e94ad17c598e42e5ec2f522a05bf4df6a1778da" ) }, { 900000, bts::blockchain::block_id_type( "a78e09bf1fd13bcd7b0959bc0764fe45db0a652d" ) }, { 1000000, bts::blockchain::block_id_type( "20da1352f86f0fc7d5b42f5e96be86ea5b219b6f" ) }, { 1100000, bts::blockchain::block_id_type( "bec7da4758ad453a49a9d9d4128acb92a1fdfd04" ) }, { 1200000, bts::blockchain::block_id_type( "9e514e0f0a17d78be7c0045f9f22a253812c6c92" ) }, { 1300000, bts::blockchain::block_id_type( "623e5c04a77b7e688299a45bfb1d84a0bf3ea318" ) }, { 1400000, bts::blockchain::block_id_type( "f7645d369b7a818c4acb94f3bedbcb7747dea9dd" ) }, { 1500000, bts::blockchain::block_id_type( "a9027b880105fa89f4d0c2bf9a0df328fed3108d" ) }, { 1600000, bts::blockchain::block_id_type( "1c08742243deda31c663130fca9ab8bd825803c5" ) }, { 1652000, bts::blockchain::block_id_type( "4ca86f5f7d9afd7c60a50a2d0886bed83dd354c9" ) } }; // Initialized in load_checkpoints() static uint32_t LAST_CHECKPOINT_BLOCK_NUM = 0; } } // bts::blockchain <commit_msg>Update checkpoints<commit_after>#pragma once #include <bts/blockchain/types.hpp> namespace bts { namespace blockchain { static std::unordered_map<uint32_t, bts::blockchain::block_id_type> CHECKPOINT_BLOCKS { { 1, bts::blockchain::block_id_type( "8abcfb93c52f999e3ef5288c4f837f4f15af5521" ) }, { 100000, bts::blockchain::block_id_type( "96f98d49722848a6a47ad04aece8b9f93c9e9c23" ) }, { 200000, bts::blockchain::block_id_type( "222ddc49db592103c51ad22cdc4140185ef564d9" ) }, { 300000, bts::blockchain::block_id_type( "0d1d0b8f7f1f4590f8e083edc03869383ed74e3e" ) }, { 400000, bts::blockchain::block_id_type( "053d398b6597d5c61365afd100d87b824bf49f65" ) }, { 500000, bts::blockchain::block_id_type( "f02910a7115fb826984ce3a432cb371d5d7a99b8" ) }, { 600000, bts::blockchain::block_id_type( "f278db8722235343c9db9f077fe67c54a5f25f3b" ) }, { 700000, bts::blockchain::block_id_type( "f120ff9b159661b9ac084a0a69c58dcbd79cbb49" ) }, { 800000, bts::blockchain::block_id_type( "0e94ad17c598e42e5ec2f522a05bf4df6a1778da" ) }, { 900000, bts::blockchain::block_id_type( "a78e09bf1fd13bcd7b0959bc0764fe45db0a652d" ) }, { 1000000, bts::blockchain::block_id_type( "20da1352f86f0fc7d5b42f5e96be86ea5b219b6f" ) }, { 1100000, bts::blockchain::block_id_type( "bec7da4758ad453a49a9d9d4128acb92a1fdfd04" ) }, { 1200000, bts::blockchain::block_id_type( "9e514e0f0a17d78be7c0045f9f22a253812c6c92" ) }, { 1300000, bts::blockchain::block_id_type( "623e5c04a77b7e688299a45bfb1d84a0bf3ea318" ) }, { 1400000, bts::blockchain::block_id_type( "f7645d369b7a818c4acb94f3bedbcb7747dea9dd" ) }, { 1500000, bts::blockchain::block_id_type( "a9027b880105fa89f4d0c2bf9a0df328fed3108d" ) }, { 1600000, bts::blockchain::block_id_type( "1c08742243deda31c663130fca9ab8bd825803c5" ) }, { 1700000, bts::blockchain::block_id_type( "52f81f9d25f379271cb2ec588b88c636996b18aa" ) }, { 1720000, bts::blockchain::block_id_type( "0acc2d561376c87600c686f019adf9883486165c" ) } }; // Initialized in load_checkpoints() static uint32_t LAST_CHECKPOINT_BLOCK_NUM = 0; } } // bts::blockchain <|endoftext|>
<commit_before>/** @file bts/blockchain/fork_blocks.hpp * @brief Defines global block number constants for when hardforks take effect */ #pragma once #include <stdint.h> #include <vector> #define BTS_EXPECTED_CHAIN_ID digest_type( "6984e235f2573526db030e92f4844312ee93d63068c5224506a34a9c0b7b5db7" ) #define BTS_DESIRED_CHAIN_ID digest_type( "2fbac26f05df0f2e8a66794d7d9eeae8a14d1478c040fb9ec02b4e6a9b09971e" ) #define BTS_V0_4_0_FORK_BLOCK_NUM 0 #define BTS_V0_4_9_FORK_BLOCK_NUM 0 #define BTS_V0_4_9_FORK_2_BLOCK_NUM 0 #define BTS_V0_4_10_FORK_BLOCK_NUM 0 #define BTS_V0_4_12_FORK_BLOCK_NUM 0 #define BTS_V0_4_13_FORK_BLOCK_NUM 0 #define BTS_V0_4_15_FORK_BLOCK_NUM 0 #define BTS_V0_4_16_FORK_BLOCK_NUM 0 #define BTS_V0_4_17_FORK_BLOCK_NUM 0 #define BTS_V0_4_18_FORK_BLOCK_NUM 0 #define BTS_V0_4_19_FORK_BLOCK_NUM 0 #define BTS_V0_4_21_FORK_BLOCK_NUM 0 #define BTS_V0_4_23_FORK_BLOCK_NUM 0 #define BTS_V0_4_24_FORK_BLOCK_NUM 0 #define BTS_V0_4_26_FORK_BLOCK_NUM 0 #define BTS_V0_5_0_FORK_BLOCK_NUM 25000 #define BTS_V0_6_0_FORK_BLOCK_NUM 120000 #define BTS_V0_6_1_FORK_BLOCK_NUM 129600 #define BTS_V0_6_2_FORK_BLOCK_NUM 187000 #define BTS_V0_6_3_FORK_BLOCK_NUM 237500 #define BTS_V0_7_0_FORK_BLOCK_NUM 9999999 #define BTS_V0_8_0_FORK_BLOCK_NUM BTS_V0_7_0_FORK_BLOCK_NUM #define BTS_V0_9_0_FORK_BLOCK_NUM BTS_V0_8_0_FORK_BLOCK_NUM #define BTS_FORK_TO_UNIX_TIME_LIST ((BTS_V0_5_0_FORK_BLOCK_NUM, "0.5.0", 1420737680)) \ ((BTS_V0_6_0_FORK_BLOCK_NUM, "0.6.0", 1421716727)) \ ((BTS_V0_6_1_FORK_BLOCK_NUM, "0.6.1", 1421879633)) \ ((BTS_V0_6_2_FORK_BLOCK_NUM, "0.6.2", 1422474382)) \ ((BTS_V0_6_3_FORK_BLOCK_NUM, "0.6.3", 1422998567)) namespace bts { namespace blockchain { uint32_t estimate_last_known_fork_from_git_revision_timestamp(uint32_t revision_time); std::vector<uint32_t> get_list_of_fork_block_numbers(); } } <commit_msg>Set fork block num<commit_after>/** @file bts/blockchain/fork_blocks.hpp * @brief Defines global block number constants for when hardforks take effect */ #pragma once #include <stdint.h> #include <vector> #define BTS_EXPECTED_CHAIN_ID digest_type( "6984e235f2573526db030e92f4844312ee93d63068c5224506a34a9c0b7b5db7" ) #define BTS_DESIRED_CHAIN_ID digest_type( "2fbac26f05df0f2e8a66794d7d9eeae8a14d1478c040fb9ec02b4e6a9b09971e" ) #define BTS_V0_4_0_FORK_BLOCK_NUM 0 #define BTS_V0_4_9_FORK_BLOCK_NUM 0 #define BTS_V0_4_9_FORK_2_BLOCK_NUM 0 #define BTS_V0_4_10_FORK_BLOCK_NUM 0 #define BTS_V0_4_12_FORK_BLOCK_NUM 0 #define BTS_V0_4_13_FORK_BLOCK_NUM 0 #define BTS_V0_4_15_FORK_BLOCK_NUM 0 #define BTS_V0_4_16_FORK_BLOCK_NUM 0 #define BTS_V0_4_17_FORK_BLOCK_NUM 0 #define BTS_V0_4_18_FORK_BLOCK_NUM 0 #define BTS_V0_4_19_FORK_BLOCK_NUM 0 #define BTS_V0_4_21_FORK_BLOCK_NUM 0 #define BTS_V0_4_23_FORK_BLOCK_NUM 0 #define BTS_V0_4_24_FORK_BLOCK_NUM 0 #define BTS_V0_4_26_FORK_BLOCK_NUM 0 #define BTS_V0_5_0_FORK_BLOCK_NUM 25000 #define BTS_V0_6_0_FORK_BLOCK_NUM 120000 #define BTS_V0_6_1_FORK_BLOCK_NUM 129600 #define BTS_V0_6_2_FORK_BLOCK_NUM 187000 #define BTS_V0_6_3_FORK_BLOCK_NUM 237500 #define BTS_V0_7_0_FORK_BLOCK_NUM 650000 #define BTS_V0_8_0_FORK_BLOCK_NUM BTS_V0_7_0_FORK_BLOCK_NUM #define BTS_V0_9_0_FORK_BLOCK_NUM BTS_V0_8_0_FORK_BLOCK_NUM #define BTS_FORK_TO_UNIX_TIME_LIST ((BTS_V0_5_0_FORK_BLOCK_NUM, "0.5.0", 1420737680)) \ ((BTS_V0_6_0_FORK_BLOCK_NUM, "0.6.0", 1421716727)) \ ((BTS_V0_6_1_FORK_BLOCK_NUM, "0.6.1", 1421879633)) \ ((BTS_V0_6_2_FORK_BLOCK_NUM, "0.6.2", 1422474382)) \ ((BTS_V0_6_3_FORK_BLOCK_NUM, "0.6.3", 1422998567)) //((BTS_V0_9_0_FORK_BLOCK_NUM, "0.9.0", 1422998567)) namespace bts { namespace blockchain { uint32_t estimate_last_known_fork_from_git_revision_timestamp(uint32_t revision_time); std::vector<uint32_t> get_list_of_fork_block_numbers(); } } <|endoftext|>
<commit_before>/* Copyright (C) 2001 by Jorrit Tyberghein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "cssys/system.h" #include "csutil/cscolor.h" #include "cstool/csview.h" #include "cstool/initapp.h" #include "simple2.h" #include "iutil/eventq.h" #include "iutil/event.h" #include "iutil/objreg.h" #include "iutil/csinput.h" #include "iengine/sector.h" #include "iengine/engine.h" #include "iengine/camera.h" #include "iengine/light.h" #include "iengine/statlght.h" #include "iengine/texture.h" #include "iengine/mesh.h" #include "iengine/movable.h" #include "iengine/material.h" #include "imesh/thing/polygon.h" #include "imesh/thing/thing.h" #include "imesh/object.h" #include "imesh/sprite3d.h" #include "ivideo/graph3d.h" #include "ivideo/graph2d.h" #include "ivideo/txtmgr.h" #include "ivideo/texture.h" #include "ivideo/material.h" #include "imap/parser.h" #include "ivaria/reporter.h" CS_IMPLEMENT_APPLICATION //----------------------------------------------------------------------------- // The global system driver Simple *System; Simple::Simple () { view = NULL; engine = NULL; loader = NULL; g3d = NULL; kbd = NULL; } Simple::~Simple () { if (view) view->DecRef (); if (engine) engine->DecRef (); if (loader) loader->DecRef(); if (g3d) g3d->DecRef (); if (kbd) kbd->DecRef (); } void Cleanup () { csPrintf ("Cleaning up...\n"); delete System; } bool Simple::Initialize (int argc, const char* const argv[], const char *iConfigName) { if (!superclass::Initialize (argc, argv, iConfigName)) return false; iObjectRegistry* object_reg = GetObjectRegistry (); if (!csInitializeApplication (object_reg)) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "couldn't init app! (perhaps some plugins are missing?)"); return false; } // Find the pointer to engine plugin engine = CS_QUERY_REGISTRY (object_reg, iEngine); if (!engine) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "No iEngine plugin!"); exit (1); } engine->IncRef (); loader = CS_QUERY_REGISTRY (object_reg, iLoader); if (!loader) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "No iLoader plugin!"); exit (1); } loader->IncRef (); g3d = CS_QUERY_REGISTRY (object_reg, iGraphics3D); if (!g3d) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "No iGraphics3D plugin!"); exit (1); } g3d->IncRef (); kbd = CS_QUERY_REGISTRY (object_reg, iKeyboardDriver); if (!kbd) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "No iKeyboardDriver plugin!"); exit (1); } kbd->IncRef(); // Open the main system. This will open all the previously loaded plug-ins. if (!Open ()) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "Error opening system!"); Cleanup (); exit (1); } // Setup the texture manager iTextureManager* txtmgr = g3d->GetTextureManager (); txtmgr->SetVerbose (true); // Initialize the texture manager txtmgr->ResetPalette (); csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY, "crystalspace.application.simple2", "Simple Crystal Space Application version 0.1."); // First disable the lighting cache. Our app is simple enough // not to need this. engine->SetLightingCacheMode (0); // Create our world. csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY, "crystalspace.application.simple2", "Creating world!..."); if (!loader->LoadTexture ("stone", "/lib/std/stone4.gif")) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "Error loading 'stone4' texture!"); Cleanup (); exit (1); } iMaterialWrapper* tm = engine->GetMaterialList ()->FindByName ("stone"); room = engine->CreateSector ("room"); iMeshWrapper* walls = engine->CreateSectorWallsMesh (room, "walls"); iThingState* walls_state = SCF_QUERY_INTERFACE (walls->GetMeshObject (), iThingState); iPolygon3D* p; p = walls_state->CreatePolygon (); p->SetMaterial (tm); p->CreateVertex (csVector3 (-5, 0, 5)); p->CreateVertex (csVector3 (5, 0, 5)); p->CreateVertex (csVector3 (5, 0, -5)); p->CreateVertex (csVector3 (-5, 0, -5)); p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3); p = walls_state->CreatePolygon (); p->SetMaterial (tm); p->CreateVertex (csVector3 (-5, 20, -5)); p->CreateVertex (csVector3 (5, 20, -5)); p->CreateVertex (csVector3 (5, 20, 5)); p->CreateVertex (csVector3 (-5, 20, 5)); p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3); p = walls_state->CreatePolygon (); p->SetMaterial (tm); p->CreateVertex (csVector3 (-5, 20, 5)); p->CreateVertex (csVector3 (5, 20, 5)); p->CreateVertex (csVector3 (5, 0, 5)); p->CreateVertex (csVector3 (-5, 0, 5)); p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3); p = walls_state->CreatePolygon (); p->SetMaterial (tm); p->CreateVertex (csVector3 (5, 20, 5)); p->CreateVertex (csVector3 (5, 20, -5)); p->CreateVertex (csVector3 (5, 0, -5)); p->CreateVertex (csVector3 (5, 0, 5)); p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3); p = walls_state->CreatePolygon (); p->SetMaterial (tm); p->CreateVertex (csVector3 (-5, 20, -5)); p->CreateVertex (csVector3 (-5, 20, 5)); p->CreateVertex (csVector3 (-5, 0, 5)); p->CreateVertex (csVector3 (-5, 0, -5)); p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3); p = walls_state->CreatePolygon (); p->SetMaterial (tm); p->CreateVertex (csVector3 (5, 20, -5)); p->CreateVertex (csVector3 (-5, 20, -5)); p->CreateVertex (csVector3 (-5, 0, -5)); p->CreateVertex (csVector3 (5, 0, -5)); p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3); walls_state->DecRef (); walls->DecRef (); iStatLight* light; iLightList* ll = room->GetLights (); light = engine->CreateLight (NULL, csVector3 (-3, 5, 0), 10, csColor (1, 0, 0), false); ll->AddLight (light->QueryLight ()); light->DecRef (); light = engine->CreateLight (NULL, csVector3 (3, 5, 0), 10, csColor (0, 0, 1), false); ll->AddLight (light->QueryLight ()); light->DecRef (); light = engine->CreateLight (NULL, csVector3 (0, 5, -3), 10, csColor (0, 1, 0), false); ll->AddLight (light->QueryLight ()); light->DecRef (); engine->Prepare (); csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY, "crystalspace.application.simple2", "Created."); view = new csView (engine, g3d); view->GetCamera ()->SetSector (room); view->GetCamera ()->GetTransform ().SetOrigin (csVector3 (0, 5, -3)); iGraphics2D* g2d = g3d->GetDriver2D (); view->SetRectangle (0, 0, g2d->GetWidth (), g2d->GetHeight ()); txtmgr->SetPalette (); // Load a texture for our sprite. iTextureWrapper* txt = loader->LoadTexture ("spark", "/lib/std/spark.png"); if (txt == NULL) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "Error loading texture!"); Cleanup (); exit (1); } txt->Register (txtmgr); txt->GetTextureHandle()->Prepare (); iMaterialWrapper* mat = engine->GetMaterialList ()->FindByName ("spark"); mat->Register (txtmgr); mat->GetMaterialHandle ()->Prepare (); // Load a sprite template from disk. iMeshFactoryWrapper* imeshfact = loader->LoadMeshObjectFactory ( "/lib/std/sprite1"); if (imeshfact == NULL) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "Error loading mesh object factory!"); Cleanup (); exit (1); } // Add the sprite to the engine. iMeshWrapper* sprite = engine->CreateMeshWrapper ( imeshfact, "MySprite", room, csVector3 (-3, 5, 3)); csMatrix3 m; m.Identity (); m *= 5.; sprite->GetMovable ()->SetTransform (m); sprite->GetMovable ()->UpdateMove (); iSprite3DState* spstate = SCF_QUERY_INTERFACE (sprite->GetMeshObject (), iSprite3DState); spstate->SetAction ("default"); imeshfact->DecRef (); spstate->DecRef (); sprite->DeferUpdateLighting (CS_NLIGHT_STATIC|CS_NLIGHT_DYNAMIC, 10); return true; } bool Simple::HandleEvent (iEvent& Event) { if (superclass::HandleEvent (Event)) return true; if (Event.Type == csevKeyDown && Event.Key.Code == CSKEY_ESC) { iEventQueue* q = CS_QUERY_REGISTRY (GetObjectRegistry (), iEventQueue); if (q) q->GetEventOutlet()->Broadcast (cscmdQuit); return true; } return false; } void Simple::NextFrame () { superclass::NextFrame (); // First get elapsed time from the system driver. csTicks elapsed_time, current_time; GetElapsedTime (elapsed_time, current_time); // Now rotate the camera according to keyboard state float speed = (elapsed_time / 1000.0) * (0.03 * 20); iCamera* c = view->GetCamera(); if (kbd->GetKeyState (CSKEY_RIGHT)) c->GetTransform ().RotateThis (VEC_ROT_RIGHT, speed); if (kbd->GetKeyState (CSKEY_LEFT)) c->GetTransform ().RotateThis (VEC_ROT_LEFT, speed); if (kbd->GetKeyState (CSKEY_PGUP)) c->GetTransform ().RotateThis (VEC_TILT_UP, speed); if (kbd->GetKeyState (CSKEY_PGDN)) c->GetTransform ().RotateThis (VEC_TILT_DOWN, speed); if (kbd->GetKeyState (CSKEY_UP)) c->Move (VEC_FORWARD * 4 * speed); if (kbd->GetKeyState (CSKEY_DOWN)) c->Move (VEC_BACKWARD * 4 * speed); // Tell 3D driver we're going to display 3D things. if (!g3d->BeginDraw ( engine->GetBeginDrawFlags () | CSDRAW_3DGRAPHICS)) return; // Tell the camera to render into the frame buffer. view->Draw (); // Drawing code ends here. g3d->FinishDraw (); // Display the final output. g3d->Print (NULL); } /*---------------------------------------------------------------------* * Main function *---------------------------------------------------------------------*/ int main (int argc, char* argv[]) { srand (time (NULL)); // Create our main class. System = new Simple (); // We want at least the minimal set of plugins System->RequestPlugin ("crystalspace.kernel.vfs:VFS"); //@@@ WHY IS THE FONTSERVER NEEDED FOR OPENGL AND NOT FOR SOFTWARE??? System->RequestPlugin ("crystalspace.font.server.default:FontServer"); System->RequestPlugin ("crystalspace.graphic.image.io.multiplex:ImageLoader"); System->RequestPlugin ("crystalspace.graphics3d.software:VideoDriver"); System->RequestPlugin ("crystalspace.engine.3d:Engine"); System->RequestPlugin ("crystalspace.level.loader:LevelLoader"); // Initialize the main system. This will load all needed plug-ins // (3D, 2D, network, sound, ...) and initialize them. if (!System->Initialize (argc, argv, NULL)) { csReport (System->GetObjectRegistry (), CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "Error initializing system!"); Cleanup (); exit (1); } // Main loop. System->Loop (); // Cleanup. Cleanup (); return 0; } <commit_msg>added decref'ing of the created meshwrapper, now simple2 also cleanly unloads the 3d meshobject factory plugin<commit_after>/* Copyright (C) 2001 by Jorrit Tyberghein This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "cssys/system.h" #include "csutil/cscolor.h" #include "cstool/csview.h" #include "cstool/initapp.h" #include "simple2.h" #include "iutil/eventq.h" #include "iutil/event.h" #include "iutil/objreg.h" #include "iutil/csinput.h" #include "iengine/sector.h" #include "iengine/engine.h" #include "iengine/camera.h" #include "iengine/light.h" #include "iengine/statlght.h" #include "iengine/texture.h" #include "iengine/mesh.h" #include "iengine/movable.h" #include "iengine/material.h" #include "imesh/thing/polygon.h" #include "imesh/thing/thing.h" #include "imesh/object.h" #include "imesh/sprite3d.h" #include "ivideo/graph3d.h" #include "ivideo/graph2d.h" #include "ivideo/txtmgr.h" #include "ivideo/texture.h" #include "ivideo/material.h" #include "imap/parser.h" #include "ivaria/reporter.h" CS_IMPLEMENT_APPLICATION //----------------------------------------------------------------------------- // The global system driver Simple *System; Simple::Simple () { view = NULL; engine = NULL; loader = NULL; g3d = NULL; kbd = NULL; } Simple::~Simple () { if (view) view->DecRef (); if (engine) engine->DecRef (); if (loader) loader->DecRef(); if (g3d) g3d->DecRef (); if (kbd) kbd->DecRef (); } void Cleanup () { csPrintf ("Cleaning up...\n"); delete System; } bool Simple::Initialize (int argc, const char* const argv[], const char *iConfigName) { if (!superclass::Initialize (argc, argv, iConfigName)) return false; iObjectRegistry* object_reg = GetObjectRegistry (); if (!csInitializeApplication (object_reg)) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "couldn't init app! (perhaps some plugins are missing?)"); return false; } // Find the pointer to engine plugin engine = CS_QUERY_REGISTRY (object_reg, iEngine); if (!engine) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "No iEngine plugin!"); exit (1); } engine->IncRef (); loader = CS_QUERY_REGISTRY (object_reg, iLoader); if (!loader) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "No iLoader plugin!"); exit (1); } loader->IncRef (); g3d = CS_QUERY_REGISTRY (object_reg, iGraphics3D); if (!g3d) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "No iGraphics3D plugin!"); exit (1); } g3d->IncRef (); kbd = CS_QUERY_REGISTRY (object_reg, iKeyboardDriver); if (!kbd) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "No iKeyboardDriver plugin!"); exit (1); } kbd->IncRef(); // Open the main system. This will open all the previously loaded plug-ins. if (!Open ()) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "Error opening system!"); Cleanup (); exit (1); } // Setup the texture manager iTextureManager* txtmgr = g3d->GetTextureManager (); txtmgr->SetVerbose (true); // Initialize the texture manager txtmgr->ResetPalette (); csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY, "crystalspace.application.simple2", "Simple Crystal Space Application version 0.1."); // First disable the lighting cache. Our app is simple enough // not to need this. engine->SetLightingCacheMode (0); // Create our world. csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY, "crystalspace.application.simple2", "Creating world!..."); if (!loader->LoadTexture ("stone", "/lib/std/stone4.gif")) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "Error loading 'stone4' texture!"); Cleanup (); exit (1); } iMaterialWrapper* tm = engine->GetMaterialList ()->FindByName ("stone"); room = engine->CreateSector ("room"); iMeshWrapper* walls = engine->CreateSectorWallsMesh (room, "walls"); iThingState* walls_state = SCF_QUERY_INTERFACE (walls->GetMeshObject (), iThingState); iPolygon3D* p; p = walls_state->CreatePolygon (); p->SetMaterial (tm); p->CreateVertex (csVector3 (-5, 0, 5)); p->CreateVertex (csVector3 (5, 0, 5)); p->CreateVertex (csVector3 (5, 0, -5)); p->CreateVertex (csVector3 (-5, 0, -5)); p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3); p = walls_state->CreatePolygon (); p->SetMaterial (tm); p->CreateVertex (csVector3 (-5, 20, -5)); p->CreateVertex (csVector3 (5, 20, -5)); p->CreateVertex (csVector3 (5, 20, 5)); p->CreateVertex (csVector3 (-5, 20, 5)); p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3); p = walls_state->CreatePolygon (); p->SetMaterial (tm); p->CreateVertex (csVector3 (-5, 20, 5)); p->CreateVertex (csVector3 (5, 20, 5)); p->CreateVertex (csVector3 (5, 0, 5)); p->CreateVertex (csVector3 (-5, 0, 5)); p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3); p = walls_state->CreatePolygon (); p->SetMaterial (tm); p->CreateVertex (csVector3 (5, 20, 5)); p->CreateVertex (csVector3 (5, 20, -5)); p->CreateVertex (csVector3 (5, 0, -5)); p->CreateVertex (csVector3 (5, 0, 5)); p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3); p = walls_state->CreatePolygon (); p->SetMaterial (tm); p->CreateVertex (csVector3 (-5, 20, -5)); p->CreateVertex (csVector3 (-5, 20, 5)); p->CreateVertex (csVector3 (-5, 0, 5)); p->CreateVertex (csVector3 (-5, 0, -5)); p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3); p = walls_state->CreatePolygon (); p->SetMaterial (tm); p->CreateVertex (csVector3 (5, 20, -5)); p->CreateVertex (csVector3 (-5, 20, -5)); p->CreateVertex (csVector3 (-5, 0, -5)); p->CreateVertex (csVector3 (5, 0, -5)); p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3); walls_state->DecRef (); walls->DecRef (); iStatLight* light; iLightList* ll = room->GetLights (); light = engine->CreateLight (NULL, csVector3 (-3, 5, 0), 10, csColor (1, 0, 0), false); ll->AddLight (light->QueryLight ()); light->DecRef (); light = engine->CreateLight (NULL, csVector3 (3, 5, 0), 10, csColor (0, 0, 1), false); ll->AddLight (light->QueryLight ()); light->DecRef (); light = engine->CreateLight (NULL, csVector3 (0, 5, -3), 10, csColor (0, 1, 0), false); ll->AddLight (light->QueryLight ()); light->DecRef (); engine->Prepare (); csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY, "crystalspace.application.simple2", "Created."); view = new csView (engine, g3d); view->GetCamera ()->SetSector (room); view->GetCamera ()->GetTransform ().SetOrigin (csVector3 (0, 5, -3)); iGraphics2D* g2d = g3d->GetDriver2D (); view->SetRectangle (0, 0, g2d->GetWidth (), g2d->GetHeight ()); txtmgr->SetPalette (); // Load a texture for our sprite. iTextureWrapper* txt = loader->LoadTexture ("spark", "/lib/std/spark.png"); if (txt == NULL) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "Error loading texture!"); Cleanup (); exit (1); } txt->Register (txtmgr); txt->GetTextureHandle()->Prepare (); iMaterialWrapper* mat = engine->GetMaterialList ()->FindByName ("spark"); mat->Register (txtmgr); mat->GetMaterialHandle ()->Prepare (); // Load a sprite template from disk. iMeshFactoryWrapper* imeshfact = loader->LoadMeshObjectFactory ( "/lib/std/sprite1"); if (imeshfact == NULL) { csReport (object_reg, CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "Error loading mesh object factory!"); Cleanup (); exit (1); } // Add the sprite to the engine. iMeshWrapper* sprite = engine->CreateMeshWrapper ( imeshfact, "MySprite", room, csVector3 (-3, 5, 3)); csMatrix3 m; m.Identity (); m *= 5.; sprite->GetMovable ()->SetTransform (m); sprite->GetMovable ()->UpdateMove (); iSprite3DState* spstate = SCF_QUERY_INTERFACE (sprite->GetMeshObject (), iSprite3DState); spstate->SetAction ("default"); imeshfact->DecRef (); spstate->DecRef (); sprite->DeferUpdateLighting (CS_NLIGHT_STATIC|CS_NLIGHT_DYNAMIC, 10); sprite->DecRef (); return true; } bool Simple::HandleEvent (iEvent& Event) { if (superclass::HandleEvent (Event)) return true; if (Event.Type == csevKeyDown && Event.Key.Code == CSKEY_ESC) { iEventQueue* q = CS_QUERY_REGISTRY (GetObjectRegistry (), iEventQueue); if (q) q->GetEventOutlet()->Broadcast (cscmdQuit); return true; } return false; } void Simple::NextFrame () { superclass::NextFrame (); // First get elapsed time from the system driver. csTicks elapsed_time, current_time; GetElapsedTime (elapsed_time, current_time); // Now rotate the camera according to keyboard state float speed = (elapsed_time / 1000.0) * (0.03 * 20); iCamera* c = view->GetCamera(); if (kbd->GetKeyState (CSKEY_RIGHT)) c->GetTransform ().RotateThis (VEC_ROT_RIGHT, speed); if (kbd->GetKeyState (CSKEY_LEFT)) c->GetTransform ().RotateThis (VEC_ROT_LEFT, speed); if (kbd->GetKeyState (CSKEY_PGUP)) c->GetTransform ().RotateThis (VEC_TILT_UP, speed); if (kbd->GetKeyState (CSKEY_PGDN)) c->GetTransform ().RotateThis (VEC_TILT_DOWN, speed); if (kbd->GetKeyState (CSKEY_UP)) c->Move (VEC_FORWARD * 4 * speed); if (kbd->GetKeyState (CSKEY_DOWN)) c->Move (VEC_BACKWARD * 4 * speed); // Tell 3D driver we're going to display 3D things. if (!g3d->BeginDraw ( engine->GetBeginDrawFlags () | CSDRAW_3DGRAPHICS)) return; // Tell the camera to render into the frame buffer. view->Draw (); // Drawing code ends here. g3d->FinishDraw (); // Display the final output. g3d->Print (NULL); } /*---------------------------------------------------------------------* * Main function *---------------------------------------------------------------------*/ int main (int argc, char* argv[]) { srand (time (NULL)); // Create our main class. System = new Simple (); // We want at least the minimal set of plugins System->RequestPlugin ("crystalspace.kernel.vfs:VFS"); //@@@ WHY IS THE FONTSERVER NEEDED FOR OPENGL AND NOT FOR SOFTWARE??? System->RequestPlugin ("crystalspace.font.server.default:FontServer"); System->RequestPlugin ("crystalspace.graphic.image.io.multiplex:ImageLoader"); System->RequestPlugin ("crystalspace.graphics3d.software:VideoDriver"); System->RequestPlugin ("crystalspace.engine.3d:Engine"); System->RequestPlugin ("crystalspace.level.loader:LevelLoader"); // Initialize the main system. This will load all needed plug-ins // (3D, 2D, network, sound, ...) and initialize them. if (!System->Initialize (argc, argv, NULL)) { csReport (System->GetObjectRegistry (), CS_REPORTER_SEVERITY_ERROR, "crystalspace.application.simple2", "Error initializing system!"); Cleanup (); exit (1); } // Main loop. System->Loop (); // Cleanup. Cleanup (); return 0; } <|endoftext|>
<commit_before>#include "sniffer.h" #include "util.h" #include <cstdlib> #include <pcap.h> static pcap_t *handle = NULL; void initialize(char * interface) { if ( handle ) { error("Trying to reinitialize using interface %s",interface); abort(); } char errbuf[BUFSIZ]; handle = pcap_open_live(interface, BUFSIZ, 1, 1000, errbuf); if (handle == NULL) { error("Couldn't open interface %s",interface); abort(); } verbose("Opened interface %s.",interface); debug("Datalink is %d.",pcap_datalink(handle)); } <commit_msg>Add basic functions<commit_after>#include "sniffer.h" #include "util.h" #include <cstdlib> #include <cstring> #include <string> #include <pcap.h> using namespace std; static pcap_t *handle = NULL; static int datalink; void initialize(char * interface) { if ( handle ) { error("Trying to reinitialize using interface %s",interface); abort(); } char errbuf[BUFSIZ]; handle = pcap_open_live(interface, BUFSIZ, 1, 1000, errbuf); if (handle == NULL) { error("Couldn't open interface %s",interface); abort(); } datalink = pcap_datalink(handle); verbose("Opened interface %s.",interface); debug("Datalink is %d.", datalink); } struct ieee80211_radiotap_header { u_int8_t it_version; /* set to 0 */ u_int8_t it_pad; u_int16_t it_len; /* entire length */ u_int32_t it_present; /* fields present */ } __attribute__((__packed__)); struct prism_value{ u_int32_t did; u_int16_t status; u_int16_t len; u_int32_t data; }; struct prism_header{ u_int32_t msgcode; u_int32_t msglen; prism_value hosttime; prism_value mactime; prism_value channel; prism_value rssi; prism_value sq; prism_value signal; prism_value noise; prism_value rate; prism_value istx; prism_value frmlen; }; void handleMAC(const u_char * mac, int pos) { char mac_c_str[13]; mac_c_str[0] = 0; for ( int i = 0 ; i < 6 ; i++ ) { sprintf(mac_c_str,"%s%02X",mac_c_str,mac[i]); } string mac_str(mac_c_str); // TODO: Add to the buckets } void handlePacket(const u_char* packet, int len) { if ( datalink == DLT_PRISM_HEADER ) { prism_header* rth1 = (prism_header*)(packet); packet = packet + rth1->msglen; } // TODO: Check if the +4 should come after this line or before (during the PRISM skip) for ( int i = 0 ; i < 3 ; i++ ) { handleMAC(packet+4+(i*6),i); } } <|endoftext|>
<commit_before>#include "Tests.h" #include "../../TestFramework/UnitTest++/UnitTest++.h" #include "../Scheduler.h" #include <Squish.h> namespace EmbeddedImage { #include "LenaColor.h" #include "LenaColorDXT1.h" } SUITE(DxtTests) { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace DxtCompress { struct TaskParams { uint32 width; uint32 height; uint32 stride; uint8 * srcPixels; uint32 blkWidth; uint32 blkHeight; uint8 * dstBlocks; }; void MT_CALL_CONV Run(MT::FiberContext&, void* userData) { const TaskParams & params = *(TaskParams*)userData; int blkHeight = params.height >> 2; int blkWidth = params.width >> 2; for (int blkY = 0; blkY < blkHeight; blkY++) { for (int blkX = 0; blkX < blkWidth; blkX++) { // 16 pixels of input uint32 pixels[4*4]; // copy dxt1 block from image for (int y = 0; y < 4; y++) { for (int x = 0; x < 4; x++) { int srcX = blkX * 4 + x; int srcY = blkY * 4 + y; int index = srcY * params.stride + (srcX * 3); uint8 r = params.srcPixels[index + 0]; uint8 g = params.srcPixels[index + 1]; uint8 b = params.srcPixels[index + 2]; uint32 color = 0xFF000000 | ((b << 16) | (g << 8) | (r)); pixels[y * 4 + x] = color; } } // 8 bytes of output int blockIndex = blkY * blkWidth + blkX; uint8 * dxtBlock = &params.dstBlocks[blockIndex*8]; // compress the 4x4 block using DXT1 compression squish::Compress( (squish::u8 *)&pixels[0], dxtBlock, squish::kDxt1 ); } // block iterator } // block iterator } // dxt compressor simple test TEST(RunSimpleDxtCompress) { static_assert(ARRAY_SIZE(EmbeddedImage::lenaColor) == 49152, "Image size is invalid"); static_assert(ARRAY_SIZE(EmbeddedImage::lenaColorDXT1) == 8192, "Image size is invalid"); TaskParams taskParams; taskParams.width = 128; taskParams.height = 128; taskParams.stride = 384; taskParams.srcPixels = (uint8 *)&EmbeddedImage::lenaColor[0]; ASSERT ((taskParams.width & 3) == 0 && (taskParams.height & 4) == 0, "Image size must be a multiple of 4"); taskParams.blkWidth = taskParams.width >> 2; taskParams.blkHeight = taskParams.height >> 2; int dxtBlocksTotalSize = taskParams.blkWidth * taskParams.blkHeight * 8; taskParams.dstBlocks = (uint8 *)malloc( dxtBlocksTotalSize ); memset(taskParams.dstBlocks, 0x0, dxtBlocksTotalSize); MT::TaskScheduler scheduler; MT::TaskDesc task(DxtCompress::Run, &taskParams); scheduler.RunTasks(MT::TaskGroup::GROUP_0, &task, 1); CHECK(scheduler.WaitAll(30000)); CHECK_ARRAY_EQUAL(taskParams.dstBlocks, EmbeddedImage::lenaColorDXT1, dxtBlocksTotalSize); /* FILE * file = fopen("lena_dxt1.dds", "w+b"); fwrite(&EmbeddedImage::ddsHeader[0], ARRAY_SIZE(EmbeddedImage::ddsHeader), 1, file); fwrite(taskParams.dstBlocks, dxtBlocksTotalSize, 1, file); fclose(file); */ free(taskParams.dstBlocks); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// }<commit_msg>small test fix<commit_after>#include "Tests.h" #include "../../TestFramework/UnitTest++/UnitTest++.h" #include "../Scheduler.h" #include <Squish.h> namespace EmbeddedImage { #include "LenaColor.h" #include "LenaColorDXT1.h" } SUITE(DxtTests) { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace DxtCompress { struct TaskParams { uint32 width; uint32 height; uint32 stride; uint8 * srcPixels; uint32 blkWidth; uint32 blkHeight; uint8 * dstBlocks; }; void MT_CALL_CONV Run(MT::FiberContext&, void* userData) { const TaskParams & params = *(TaskParams*)userData; for (uint32 blkY = 0; blkY < params.blkHeight; blkY++) { for (uint32 blkX = 0; blkX < params.blkWidth; blkX++) { // 16 pixels of input uint32 pixels[4*4]; // copy dxt1 block from image for (int y = 0; y < 4; y++) { for (int x = 0; x < 4; x++) { int srcX = blkX * 4 + x; int srcY = blkY * 4 + y; int index = srcY * params.stride + (srcX * 3); uint8 r = params.srcPixels[index + 0]; uint8 g = params.srcPixels[index + 1]; uint8 b = params.srcPixels[index + 2]; uint32 color = 0xFF000000 | ((b << 16) | (g << 8) | (r)); pixels[y * 4 + x] = color; } } // 8 bytes of output int blockIndex = blkY * params.blkWidth + blkX; uint8 * dxtBlock = &params.dstBlocks[blockIndex*8]; // compress the 4x4 block using DXT1 compression squish::Compress( (squish::u8 *)&pixels[0], dxtBlock, squish::kDxt1 ); } // block iterator } // block iterator } // dxt compressor simple test TEST(RunSimpleDxtCompress) { static_assert(ARRAY_SIZE(EmbeddedImage::lenaColor) == 49152, "Image size is invalid"); static_assert(ARRAY_SIZE(EmbeddedImage::lenaColorDXT1) == 8192, "Image size is invalid"); TaskParams taskParams; taskParams.width = 128; taskParams.height = 128; taskParams.stride = 384; taskParams.srcPixels = (uint8 *)&EmbeddedImage::lenaColor[0]; ASSERT ((taskParams.width & 3) == 0 && (taskParams.height & 4) == 0, "Image size must be a multiple of 4"); taskParams.blkWidth = taskParams.width >> 2; taskParams.blkHeight = taskParams.height >> 2; int dxtBlocksTotalSize = taskParams.blkWidth * taskParams.blkHeight * 8; taskParams.dstBlocks = (uint8 *)malloc( dxtBlocksTotalSize ); memset(taskParams.dstBlocks, 0x0, dxtBlocksTotalSize); MT::TaskScheduler scheduler; MT::TaskDesc task(DxtCompress::Run, &taskParams); scheduler.RunTasks(MT::TaskGroup::GROUP_0, &task, 1); CHECK(scheduler.WaitAll(30000)); CHECK_ARRAY_EQUAL(taskParams.dstBlocks, EmbeddedImage::lenaColorDXT1, dxtBlocksTotalSize); /* FILE * file = fopen("lena_dxt1.dds", "w+b"); fwrite(&EmbeddedImage::ddsHeader[0], ARRAY_SIZE(EmbeddedImage::ddsHeader), 1, file); fwrite(taskParams.dstBlocks, dxtBlocksTotalSize, 1, file); fclose(file); */ free(taskParams.dstBlocks); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* // dxt compressor complex test TEST(RunComplexDxtCompress) { } */ } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// }<|endoftext|>
<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH #define DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH #include <dune/stuff/la/container/pattern.hh> #include <dune/stuff/la/container/eigen.hh> #include <dune/detailed/discretizations/space/interface.hh> namespace Dune { namespace Detailed { namespace Discretizations { template <class ElementType> class ContainerFactoryEigen { public: typedef Dune::Stuff::LA::EigenRowMajorSparseMatrix<ElementType> RowMajorSparseMatrixType; typedef Dune::Stuff::LA::EigenDenseMatrix<ElementType> DenseMatrixType; typedef Dune::Stuff::LA::EigenDenseVector<ElementType> DenseVectorType; typedef Dune::Stuff::LA::SparsityPatternDefault PatternType; template <class T, class A> static RowMajorSparseMatrixType* createRowMajorSparseMatrix(const SpaceInterface<T>& testSpace, const SpaceInterface<A>& ansatzSpace) { const std::shared_ptr<const PatternType> pattern(testSpace.computePattern(ansatzSpace)); return createRowMajorSparseMatrix(testSpace, ansatzSpace, *pattern); } // static ... createRowMajorSparseMatrix(...) template <class T, class A> static RowMajorSparseMatrixType* createRowMajorSparseMatrix(const SpaceInterface<T>& testSpace, const SpaceInterface<A>& ansatzSpace, const PatternType& pattern) { return new RowMajorSparseMatrixType(testSpace.mapper().size(), ansatzSpace.mapper().size(), pattern); } // static ... createRowMajorSparseMatrix(...) template <class T, class A> static DenseMatrixType createDenseMatrix(const SpaceInterface<T>& testSpace, const SpaceInterface<A>& ansatzSpace) { return new DenseMatrixType(testSpace.mapper().size(), ansatzSpace.mapper().size()); } // static ... createDenseMatrix(...) template <class S> static DenseVectorType* createDenseVector(const SpaceInterface<S>& space) { return new DenseVectorType(space.mapper().size()); } // static ... createDenseVector(const SpaceType& space) }; // class ContainerFactoryEigen } // namespace Discretizations } // namespace Detailed } // namespace Dune #endif // DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH <commit_msg>[la.containerfactory.eigen] minor fix<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH #define DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH #include <dune/stuff/la/container/pattern.hh> #include <dune/stuff/la/container/eigen.hh> #include <dune/detailed/discretizations/space/interface.hh> namespace Dune { namespace Detailed { namespace Discretizations { template <class ElementType> class ContainerFactoryEigen { public: typedef Dune::Stuff::LA::EigenRowMajorSparseMatrix<ElementType> RowMajorSparseMatrixType; typedef Dune::Stuff::LA::EigenDenseMatrix<ElementType> DenseMatrixType; typedef Dune::Stuff::LA::EigenDenseVector<ElementType> DenseVectorType; typedef Dune::Stuff::LA::SparsityPatternDefault PatternType; template <class T, class A> static RowMajorSparseMatrixType* createRowMajorSparseMatrix(const SpaceInterface<T>& testSpace, const SpaceInterface<A>& ansatzSpace) { const std::shared_ptr<const PatternType> pattern(testSpace.computePattern(ansatzSpace)); return createRowMajorSparseMatrix(testSpace, ansatzSpace, *pattern); } // static ... createRowMajorSparseMatrix(...) template <class T, class A> static RowMajorSparseMatrixType* createRowMajorSparseMatrix(const SpaceInterface<T>& testSpace, const SpaceInterface<A>& ansatzSpace, const PatternType& pattern) { return new RowMajorSparseMatrixType(testSpace.mapper().size(), ansatzSpace.mapper().size(), pattern); } // static ... createRowMajorSparseMatrix(...) template <class T, class A> static DenseMatrixType* createDenseMatrix(const SpaceInterface<T>& testSpace, const SpaceInterface<A>& ansatzSpace) { return new DenseMatrixType(testSpace.mapper().size(), ansatzSpace.mapper().size()); } // static ... createDenseMatrix(...) template <class S> static DenseVectorType* createDenseVector(const SpaceInterface<S>& space) { return new DenseVectorType(space.mapper().size()); } // static ... createDenseVector(const SpaceType& space) }; // class ContainerFactoryEigen } // namespace Discretizations } // namespace Detailed } // namespace Dune #endif // DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH <|endoftext|>
<commit_before>/****************************************************************/ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* All contents are licensed under LGPL V2.1 */ /* See LICENSE for full restrictions */ /****************************************************************/ #include "DerivativeSumMaterial.h" template<> InputParameters validParams<DerivativeSumMaterial>() { InputParameters params = validParams<DerivativeFunctionMaterialBase>(); params.addClassDescription("Meta-material to sum up multiple derivative materials"); params.addParam<std::vector<std::string> >("sum_materials", "Base name of the free energy function (used to name the material properties)"); //params.addParam<bool>("third_derivatives", true, "Calculate third derivatoves of the free energy"); // All arguments to the free energies being summed params.addRequiredCoupledVar("args", "Arguments of the free energy functions being summed - use vector coupling"); // Advanced arguments to construct a sum of the form \f$ c+\gamma\sum_iF_i \f$ params.addParam<std::vector<Real> >("prefactor", "Prefactor to multiply the sum term with."); params.addParam<Real>("constant", 0.0, "Constant to be added to the prefactor multiplied sum."); params.addParamNamesToGroup("prefactor constant", "Advanced"); return params; } DerivativeSumMaterial::DerivativeSumMaterial(const std::string & name, InputParameters parameters) : DerivativeFunctionMaterialBase(name, parameters), _sum_materials(getParam<std::vector<std::string> >("sum_materials")), _num_materials(_sum_materials.size()), _prefactor(_num_materials, 1.0), _constant(getParam<Real>("constant")) { // we need at least one material in the sum if (_num_materials == 0) mooseError("Please supply at least one material to sum in DerivativeSumMaterial " << name); // get prefactor values if not 1.0 std::vector<Real> p = getParam<std::vector<Real> >("prefactor"); // if prefactor is used we need the same number of prefactors as sum materials if (_num_materials == p.size()) _prefactor = p; else if (p.size() != 0) mooseError("Supply the same nummber of sum materials and prefactors."); // reserve space for summand material properties _summand_F.resize(_num_materials); _summand_dF.resize(_num_materials); _summand_d2F.resize(_num_materials); _summand_d3F.resize(_num_materials); for (unsigned int n = 0; n < _num_materials; ++n) { _summand_F[n] = & getMaterialProperty<Real>(_sum_materials[n]); _summand_dF[n].resize(_nargs); _summand_d2F[n].resize(_nargs); _summand_d3F[n].resize(_nargs); for (unsigned int i = 0; i < _nargs; ++i) { _summand_dF[n][i] = &getMaterialPropertyDerivative<Real>(_sum_materials[n], _arg_names[i]); _summand_d2F[n][i].resize(_nargs); if (_third_derivatives) _summand_d3F[n][i].resize(_nargs); for (unsigned int j = 0; j < _nargs; ++j) { _summand_d2F[n][i][j] = &getMaterialPropertyDerivative<Real>(_sum_materials[n], _arg_names[i], _arg_names[j]); if (_third_derivatives) { _summand_d3F[n][i][j].resize(_nargs); for (unsigned int k = 0; k < _nargs; ++k) _summand_d3F[n][i][j][k] = &getMaterialPropertyDerivative<Real>(_sum_materials[n], _arg_names[i], _arg_names[j], _arg_names[k]); } } } } } void DerivativeSumMaterial::computeProperties() { unsigned int i, j, k; for (_qp = 0; _qp < _qrule->n_points(); _qp++) { // set function value if (_prop_F) { (*_prop_F)[_qp] = (*_summand_F[0])[_qp] * _prefactor[0]; for (unsigned int n = 1; n < _num_materials; ++n) (*_prop_F)[_qp] += (*_summand_F[n])[_qp] * _prefactor[n]; } for (i = 0; i < _nargs; ++i) { // set first derivatives if (_prop_dF[i]) { (*_prop_dF[i])[_qp] = (*_summand_dF[0][i])[_qp] * _prefactor[0]; for (unsigned int n = 1; n < _num_materials; ++n) (*_prop_dF[i])[_qp] += (*_summand_dF[n][i])[_qp] * _prefactor[n]; } // second derivatives for (j = i; j < _nargs; ++j) { if (_prop_d2F[i][j]) { (*_prop_d2F[i][j])[_qp] = (*_summand_d2F[0][i][j])[_qp] * _prefactor[0]; for (unsigned int n = 1; n < _num_materials; ++n) (*_prop_d2F[i][j])[_qp] += (*_summand_d2F[n][i][j])[_qp] * _prefactor[n]; } // third derivatives if (_third_derivatives) { for (k = j; k < _nargs; ++k) if (_prop_d3F[i][j][k]) { (*_prop_d3F[i][j][k])[_qp] = (*_summand_d3F[0][i][j][k])[_qp] * _prefactor[0]; for (unsigned int n = 1; n < _num_materials; ++n) (*_prop_d3F[i][j][k])[_qp] += (*_summand_d3F[n][i][j][k])[_qp] * _prefactor[n]; } } } } } } <commit_msg>deleted white space in DerivativeSumMaterial<commit_after>/****************************************************************/ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* All contents are licensed under LGPL V2.1 */ /* See LICENSE for full restrictions */ /****************************************************************/ #include "DerivativeSumMaterial.h" template<> InputParameters validParams<DerivativeSumMaterial>() { InputParameters params = validParams<DerivativeFunctionMaterialBase>(); params.addClassDescription("Meta-material to sum up multiple derivative materials"); params.addParam<std::vector<std::string> >("sum_materials", "Base name of the free energy function (used to name the material properties)"); //params.addParam<bool>("third_derivatives", true, "Calculate third derivatoves of the free energy"); // All arguments to the free energies being summed params.addRequiredCoupledVar("args", "Arguments of the free energy functions being summed - use vector coupling"); // Advanced arguments to construct a sum of the form \f$ c+\gamma\sum_iF_i \f$ params.addParam<std::vector<Real> >("prefactor", "Prefactor to multiply the sum term with."); params.addParam<Real>("constant", 0.0, "Constant to be added to the prefactor multiplied sum."); params.addParamNamesToGroup("prefactor constant", "Advanced"); return params; } DerivativeSumMaterial::DerivativeSumMaterial(const std::string & name, InputParameters parameters) : DerivativeFunctionMaterialBase(name, parameters), _sum_materials(getParam<std::vector<std::string> >("sum_materials")), _num_materials(_sum_materials.size()), _prefactor(_num_materials, 1.0), _constant(getParam<Real>("constant")) { // we need at least one material in the sum if (_num_materials == 0) mooseError("Please supply at least one material to sum in DerivativeSumMaterial " << name); // get prefactor values if not 1.0 std::vector<Real> p = getParam<std::vector<Real> >("prefactor"); // if prefactor is used we need the same number of prefactors as sum materials if (_num_materials == p.size()) _prefactor = p; else if (p.size() != 0) mooseError("Supply the same nummber of sum materials and prefactors."); // reserve space for summand material properties _summand_F.resize(_num_materials); _summand_dF.resize(_num_materials); _summand_d2F.resize(_num_materials); _summand_d3F.resize(_num_materials); for (unsigned int n = 0; n < _num_materials; ++n) { _summand_F[n] = & getMaterialProperty<Real>(_sum_materials[n]); _summand_dF[n].resize(_nargs); _summand_d2F[n].resize(_nargs); _summand_d3F[n].resize(_nargs); for (unsigned int i = 0; i < _nargs; ++i) { _summand_dF[n][i] = &getMaterialPropertyDerivative<Real>(_sum_materials[n], _arg_names[i]); _summand_d2F[n][i].resize(_nargs); if (_third_derivatives) _summand_d3F[n][i].resize(_nargs); for (unsigned int j = 0; j < _nargs; ++j) { _summand_d2F[n][i][j] = &getMaterialPropertyDerivative<Real>(_sum_materials[n], _arg_names[i], _arg_names[j]); if (_third_derivatives) { _summand_d3F[n][i][j].resize(_nargs); for (unsigned int k = 0; k < _nargs; ++k) _summand_d3F[n][i][j][k] = &getMaterialPropertyDerivative<Real>(_sum_materials[n], _arg_names[i], _arg_names[j], _arg_names[k]); } } } } } void DerivativeSumMaterial::computeProperties() { unsigned int i, j, k; for (_qp = 0; _qp < _qrule->n_points(); _qp++) { // set function value if (_prop_F) { (*_prop_F)[_qp] = (*_summand_F[0])[_qp] * _prefactor[0]; for (unsigned int n = 1; n < _num_materials; ++n) (*_prop_F)[_qp] += (*_summand_F[n])[_qp] * _prefactor[n]; } for (i = 0; i < _nargs; ++i) { // set first derivatives if (_prop_dF[i]) { (*_prop_dF[i])[_qp] = (*_summand_dF[0][i])[_qp] * _prefactor[0]; for (unsigned int n = 1; n < _num_materials; ++n) (*_prop_dF[i])[_qp] += (*_summand_dF[n][i])[_qp] * _prefactor[n]; } // second derivatives for (j = i; j < _nargs; ++j) { if (_prop_d2F[i][j]) { (*_prop_d2F[i][j])[_qp] = (*_summand_d2F[0][i][j])[_qp] * _prefactor[0]; for (unsigned int n = 1; n < _num_materials; ++n) (*_prop_d2F[i][j])[_qp] += (*_summand_d2F[n][i][j])[_qp] * _prefactor[n]; } // third derivatives if (_third_derivatives) { for (k = j; k < _nargs; ++k) if (_prop_d3F[i][j][k]) { (*_prop_d3F[i][j][k])[_qp] = (*_summand_d3F[0][i][j][k])[_qp] * _prefactor[0]; for (unsigned int n = 1; n < _num_materials; ++n) (*_prop_d3F[i][j][k])[_qp] += (*_summand_d3F[n][i][j][k])[_qp] * _prefactor[n]; } } } } } } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 * * (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <sofa/component/collision/FixParticlePerformer.h> #include <sofa/component/collision/MouseInteractor.h> #include <sofa/component/constraint/FixedConstraint.h> #include <sofa/simulation/common/InitVisitor.h> #include <sofa/simulation/common/DeleteVisitor.h> namespace sofa { namespace component { namespace collision { template <class DataTypes> void FixParticlePerformer<DataTypes>::start() { core::componentmodel::behavior::MechanicalState<DataTypes>* mstateCollision=NULL; int index; typename DataTypes::Coord pointPicked; BodyPicked picked=this->interactor->getBodyPicked(); if (picked.body) { mapper = MouseContactMapper::Create(picked.body); if (!mapper) { this->interactor->serr << "Problem with Mouse Mapper creation : " << this->interactor->sendl; return; } std::string name = "contactMouse"; mstateCollision = mapper->createMapping(name.c_str()); mapper->resize(1); const int idx=picked.indexCollisionElement; pointPicked=(*(mstateCollision->getX()))[idx]; typename DataTypes::Real r=0.0; index = mapper->addPoint(pointPicked, idx, r); mapper->update(); if (mstateCollision->getContext() != picked.body->getContext()) { simulation::Node *mappedNode=(simulation::Node *) mstateCollision->getContext(); simulation::Node *mainNode=(simulation::Node *) picked.body->getContext(); core::componentmodel::behavior::BaseMechanicalState *mainDof=dynamic_cast<core::componentmodel::behavior::BaseMechanicalState *>(mainNode->getMechanicalState()); const core::objectmodel::TagSet &tags=mainDof->getTags(); for (core::objectmodel::TagSet::const_iterator it=tags.begin(); it!=tags.end(); ++it) { mstateCollision->addTag(*it); mappedNode->mechanicalMapping->addTag(*it); } mstateCollision->setName("AttachedPoint"); mappedNode->mechanicalMapping->setName("MouseMapping"); } } else { mstateCollision = dynamic_cast< core::componentmodel::behavior::MechanicalState<DataTypes>* >(picked.mstate); index = picked.indexCollisionElement; pointPicked=(*(mstateCollision->getX()))[index]; if (!mstateCollision) { this->interactor->serr << "uncompatible MState during Mouse Interaction " << this->interactor->sendl; return; } } std::string name = "contactMouse"; simulation::Node* nodeCollision = static_cast<simulation::Node*>(mstateCollision->getContext()); simulation::Node* nodeFixation = simulation::getSimulation()->newNode("FixationPoint"); fixations.push_back( nodeFixation ); MouseContainer* mstateFixation = new MouseContainer(); mstateFixation->setIgnoreLoader(true); mstateFixation->resize(1); (*mstateFixation->getX())[0] = pointPicked; nodeFixation->addObject(mstateFixation); constraint::FixedConstraint<DataTypes> *fixFixation = new constraint::FixedConstraint<DataTypes>(); nodeFixation->addObject(fixFixation); MouseForceField *distanceForceField = new MouseForceField(mstateFixation, mstateCollision); const double friction=0.0; distanceForceField->addSpring(0,index, stiffness, friction, 0); nodeFixation->addObject(distanceForceField); nodeCollision->addChild(nodeFixation); nodeFixation->updateContext(); nodeFixation->execute<simulation::InitVisitor>(); } template <class DataTypes> void FixParticlePerformer<DataTypes>::execute() { }; template <class DataTypes> void FixParticlePerformer<DataTypes>::draw() { for (unsigned int i=0; i<fixations.size(); ++i) { bool b = fixations[i]->getContext()->getShowBehaviorModels(); fixations[i]->getContext()->setShowBehaviorModels(true); simulation::getSimulation()->draw(fixations[i]); fixations[i]->getContext()->setShowBehaviorModels(b); } } template <class DataTypes> FixParticlePerformer<DataTypes>::FixParticlePerformer(BaseMouseInteractor *i):TInteractionPerformer<DataTypes>(i) { } template <class DataTypes> FixParticlePerformer<DataTypes>::~FixParticlePerformer() { delete mapper; fixations.clear(); }; } } } <commit_msg>r6421/sofa-dev : FIX: memory leak...<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 * * (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <sofa/component/collision/FixParticlePerformer.h> #include <sofa/component/collision/MouseInteractor.h> #include <sofa/component/constraint/FixedConstraint.h> #include <sofa/simulation/common/InitVisitor.h> #include <sofa/simulation/common/DeleteVisitor.h> namespace sofa { namespace component { namespace collision { template <class DataTypes> void FixParticlePerformer<DataTypes>::start() { core::componentmodel::behavior::MechanicalState<DataTypes>* mstateCollision=NULL; int index; typename DataTypes::Coord pointPicked; BodyPicked picked=this->interactor->getBodyPicked(); if (picked.body) { if (mapper) delete mapper; mapper = MouseContactMapper::Create(picked.body); if (!mapper) { this->interactor->serr << "Problem with Mouse Mapper creation : " << this->interactor->sendl; return; } std::string name = "contactMouse"; mstateCollision = mapper->createMapping(name.c_str()); mapper->resize(1); const int idx=picked.indexCollisionElement; pointPicked=(*(mstateCollision->getX()))[idx]; typename DataTypes::Real r=0.0; index = mapper->addPoint(pointPicked, idx, r); mapper->update(); if (mstateCollision->getContext() != picked.body->getContext()) { simulation::Node *mappedNode=(simulation::Node *) mstateCollision->getContext(); simulation::Node *mainNode=(simulation::Node *) picked.body->getContext(); core::componentmodel::behavior::BaseMechanicalState *mainDof=dynamic_cast<core::componentmodel::behavior::BaseMechanicalState *>(mainNode->getMechanicalState()); const core::objectmodel::TagSet &tags=mainDof->getTags(); for (core::objectmodel::TagSet::const_iterator it=tags.begin(); it!=tags.end(); ++it) { mstateCollision->addTag(*it); mappedNode->mechanicalMapping->addTag(*it); } mstateCollision->setName("AttachedPoint"); mappedNode->mechanicalMapping->setName("MouseMapping"); } } else { mstateCollision = dynamic_cast< core::componentmodel::behavior::MechanicalState<DataTypes>* >(picked.mstate); index = picked.indexCollisionElement; pointPicked=(*(mstateCollision->getX()))[index]; if (!mstateCollision) { this->interactor->serr << "uncompatible MState during Mouse Interaction " << this->interactor->sendl; return; } } std::string name = "contactMouse"; simulation::Node* nodeCollision = static_cast<simulation::Node*>(mstateCollision->getContext()); simulation::Node* nodeFixation = simulation::getSimulation()->newNode("FixationPoint"); fixations.push_back( nodeFixation ); MouseContainer* mstateFixation = new MouseContainer(); mstateFixation->setIgnoreLoader(true); mstateFixation->resize(1); (*mstateFixation->getX())[0] = pointPicked; nodeFixation->addObject(mstateFixation); constraint::FixedConstraint<DataTypes> *fixFixation = new constraint::FixedConstraint<DataTypes>(); nodeFixation->addObject(fixFixation); MouseForceField *distanceForceField = new MouseForceField(mstateFixation, mstateCollision); const double friction=0.0; distanceForceField->addSpring(0,index, stiffness, friction, 0); nodeFixation->addObject(distanceForceField); nodeCollision->addChild(nodeFixation); nodeFixation->updateContext(); nodeFixation->execute<simulation::InitVisitor>(); } template <class DataTypes> void FixParticlePerformer<DataTypes>::execute() { }; template <class DataTypes> void FixParticlePerformer<DataTypes>::draw() { for (unsigned int i=0; i<fixations.size(); ++i) { bool b = fixations[i]->getContext()->getShowBehaviorModels(); fixations[i]->getContext()->setShowBehaviorModels(true); simulation::getSimulation()->draw(fixations[i]); fixations[i]->getContext()->setShowBehaviorModels(b); } } template <class DataTypes> FixParticlePerformer<DataTypes>::FixParticlePerformer(BaseMouseInteractor *i):TInteractionPerformer<DataTypes>(i), mapper(NULL) { } template <class DataTypes> FixParticlePerformer<DataTypes>::~FixParticlePerformer() { if (mapper) delete mapper; fixations.clear(); }; } } } <|endoftext|>
<commit_before>//============================================================================= // socket.cpp // (c) 8-12-2010, Frans Spijkerman, Avans Hogeschool // enhanced for cross-platform use by Bob Polis (c) 2013 // // Implementation of classes Socket, ServerSocket and CientSocket //============================================================================= #include "Socket.h" #if defined(WIN32) || defined(WIN64) #pragma comment(lib, "wsock32.lib") // Tell linker to use this library //============================================================================= class WSA //============================================================================= // ONLY NEEDED IN MS-WINDOWS // // An instance of this class is created globally. // So constructor is automatically called before main() // and destructor is automatically called after main(). // Result: Windows Socket API is active when needed. //============================================================================= { private: WSADATA data; public: WSA() { WORD version = MAKEWORD(1,1); WSAStartup(version, &data); } ~WSA() { WSACleanup(); } } wsa; // instance #else // not Windows (POSIX system, like Linux or Mac OS X) #include <sys/socket.h> #include <sys/ioctl.h> #include <net/route.h> #include <net/if.h> #include <arpa/inet.h> #include <netinet/in.h> #include <sys/types.h> #include <netdb.h> #include <ifaddrs.h> #include <unistd.h> #include <cstring> #include <stdexcept> #endif // _WINDOWS //============================================================================= size_t Socket::read(char *buf, size_t maxlen) //============================================================================= // read binary chunk //============================================================================= { size_t len = 0; // might come in parts while (size_t n = ::recv(sok, buf + len, int(maxlen - len), 0)) { if (n == 0) break; len += n; if (len >= maxlen) break; } return len; } //============================================================================= size_t Socket::read(wchar_t *buf, size_t maxlen) //============================================================================= // read wide characters (e.g. UTF-16) //============================================================================= { return read(reinterpret_cast<char*>(buf), maxlen); } //============================================================================= size_t Socket::readline(char *buf, size_t maxlen) //============================================================================= // read a line: ignore '\r', stop at '\n' //============================================================================= { char c; size_t len = 0; while (size_t n = ::recv(sok, &c, 1, 0)) { if (n == 0) break; if (c == '\n') break; if (c != '\r') buf[len++] = c; if (len >= maxlen) break; } buf[len] = 0; return len; } //============================================================================= size_t Socket::readline(wchar_t *buf, size_t maxlen) //============================================================================= // read a line: ignore '\r', stop at '\n' //============================================================================= { wchar_t c; size_t len = 0; while (size_t n = ::recv(sok, (char*)&c, 2, 0)) { if (n == 0) break; if (c == '\n') break; if (c != '\r') buf[len++] = c; if (len >= maxlen) break; } buf[len] = 0; return len; } //============================================================================= void Socket::write(const char *buf, size_t len) //============================================================================= // write a buffer //============================================================================= { ::send(sok, buf, (int)len, 0); } //============================================================================= void Socket::write(const char *buf) //============================================================================= // write a zero delimited string //============================================================================= { ::send(sok, buf, (int)strlen(buf), 0); } //============================================================================= void Socket::write(const wchar_t *buf) //============================================================================= // write a zero delimited string //============================================================================= { ::send(sok, (const char*)buf, (int)(sizeof(wchar_t)*wcslen(buf)), 0); } //============================================================================= void Socket::writeline(const char *buf) //============================================================================= // write a zero delimited string //============================================================================= { ::send(sok, (const char*)buf, (int)(sizeof(char)*strlen(buf)), 0); ::send(sok, (const char*)"\r\n", (int)(sizeof(char)*2), 0); } //============================================================================= void Socket::writeline(const wchar_t *buf) //============================================================================= // write a zero delimited string //============================================================================= { ::send(sok, (const char*)buf, (int)(sizeof(wchar_t)*wcslen(buf)), 0); ::send(sok, (const char*)L"\r\n", (int)(sizeof(wchar_t)*2), 0); } //============================================================================= void Socket::close() //============================================================================= // close socket //============================================================================= { #if defined(WIN32) || defined(WIN64) ::closesocket(sok); #else ::close(sok); #endif sok = 0; } //============================================================================= ServerSocket::ServerSocket(int port) //============================================================================= { // Create a socket sok = ::socket(AF_INET, SOCK_STREAM, 0); if (sok == -1) throw runtime_error("error creating socket"); // Use SOCKADDR_IN to fill in address information struct sockaddr_in saServer; saServer.sin_family = AF_INET; saServer.sin_addr.s_addr = INADDR_ANY; saServer.sin_port = htons(port); // Convert int to a value for the port // Bind the socket to our local server address int e = ::bind(sok, (struct sockaddr*)&saServer, sizeof(struct sockaddr)); if (e == -1) throw runtime_error("error binding socket"); // Make the socket listen e = ::listen(sok, 100); // the number of clients that can be queued if (e == -1) throw runtime_error("error listening"); } //============================================================================= Socket *ServerSocket::accept() //============================================================================= // Wait for a client and return the connection socket //============================================================================= { int t = ::accept(sok, 0, 0); if (t == -1) throw runtime_error("error in accept"); return new Socket(t); } //============================================================================= ClientSocket::ClientSocket(const char *host, int port) //============================================================================= { // Create a socket sok = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sok == -1) throw runtime_error("error creating socket"); struct sockaddr_in dest; ::memset(&dest, 0, sizeof(dest)); dest.sin_family = AF_INET; hostent *hp; hp = ::gethostbyname(host); ::memcpy(&dest.sin_addr, hp->h_addr, hp->h_length); if (dest.sin_addr.s_addr == -1) throw runtime_error("cannot find address"); dest.sin_port = htons(port); int result = ::connect(sok, (sockaddr *)&dest, sizeof(sockaddr)); if (result == -1) throw runtime_error("error connecting"); } <commit_msg>socket carriege return fix<commit_after>//============================================================================= // socket.cpp // (c) 8-12-2010, Frans Spijkerman, Avans Hogeschool // enhanced for cross-platform use by Bob Polis (c) 2013 // // Implementation of classes Socket, ServerSocket and CientSocket //============================================================================= #include "Socket.h" #if defined(WIN32) || defined(WIN64) #pragma comment(lib, "wsock32.lib") // Tell linker to use this library //============================================================================= class WSA //============================================================================= // ONLY NEEDED IN MS-WINDOWS // // An instance of this class is created globally. // So constructor is automatically called before main() // and destructor is automatically called after main(). // Result: Windows Socket API is active when needed. //============================================================================= { private: WSADATA data; public: WSA() { WORD version = MAKEWORD(1,1); WSAStartup(version, &data); } ~WSA() { WSACleanup(); } } wsa; // instance #else // not Windows (POSIX system, like Linux or Mac OS X) #include <sys/socket.h> #include <sys/ioctl.h> #include <net/route.h> #include <net/if.h> #include <arpa/inet.h> #include <netinet/in.h> #include <sys/types.h> #include <netdb.h> #include <ifaddrs.h> #include <unistd.h> #include <cstring> #include <stdexcept> #endif // _WINDOWS //============================================================================= size_t Socket::read(char *buf, size_t maxlen) //============================================================================= // read binary chunk //============================================================================= { size_t len = 0; // might come in parts while (size_t n = ::recv(sok, buf + len, int(maxlen - len), 0)) { if (n == 0) break; len += n; if (len >= maxlen) break; } return len; } //============================================================================= size_t Socket::read(wchar_t *buf, size_t maxlen) //============================================================================= // read wide characters (e.g. UTF-16) //============================================================================= { return read(reinterpret_cast<char*>(buf), maxlen); } //============================================================================= size_t Socket::readline(char *buf, size_t maxlen) //============================================================================= // read a line: ignore '\r', stop at '\n' //============================================================================= { char c; size_t len = 0; while (size_t n = ::recv(sok, &c, 1, 0)) { if (n == 0) break; if (c == '\n') break; else buf[len++] = c; if (len >= maxlen) break; } buf[len] = 0; return len; } //============================================================================= size_t Socket::readline(wchar_t *buf, size_t maxlen) //============================================================================= // read a line: ignore '\r', stop at '\n' //============================================================================= { wchar_t c; size_t len = 0; while (size_t n = ::recv(sok, (char*)&c, 2, 0)) { if (n == 0) break; if (c == '\n') break; else buf[len++] = c; if (len >= maxlen) break; } buf[len] = 0; return len; } //============================================================================= void Socket::write(const char *buf, size_t len) //============================================================================= // write a buffer //============================================================================= { ::send(sok, buf, (int)len, 0); } //============================================================================= void Socket::write(const char *buf) //============================================================================= // write a zero delimited string //============================================================================= { ::send(sok, buf, (int)strlen(buf), 0); } //============================================================================= void Socket::write(const wchar_t *buf) //============================================================================= // write a zero delimited string //============================================================================= { ::send(sok, (const char*)buf, (int)(sizeof(wchar_t)*wcslen(buf)), 0); } //============================================================================= void Socket::writeline(const char *buf) //============================================================================= // write a zero delimited string //============================================================================= { ::send(sok, (const char*)buf, (int)(sizeof(char)*strlen(buf)), 0); ::send(sok, (const char*)"\r\n", (int)(sizeof(char)*2), 0); } //============================================================================= void Socket::writeline(const wchar_t *buf) //============================================================================= // write a zero delimited string //============================================================================= { ::send(sok, (const char*)buf, (int)(sizeof(wchar_t)*wcslen(buf)), 0); ::send(sok, (const char*)L"\r\n", (int)(sizeof(wchar_t)*2), 0); } //============================================================================= void Socket::close() //============================================================================= // close socket //============================================================================= { #if defined(WIN32) || defined(WIN64) ::closesocket(sok); #else ::close(sok); #endif sok = 0; } //============================================================================= ServerSocket::ServerSocket(int port) //============================================================================= { // Create a socket sok = ::socket(AF_INET, SOCK_STREAM, 0); if (sok == -1) throw runtime_error("error creating socket"); // Use SOCKADDR_IN to fill in address information struct sockaddr_in saServer; saServer.sin_family = AF_INET; saServer.sin_addr.s_addr = INADDR_ANY; saServer.sin_port = htons(port); // Convert int to a value for the port // Bind the socket to our local server address int e = ::bind(sok, (struct sockaddr*)&saServer, sizeof(struct sockaddr)); if (e == -1) throw runtime_error("error binding socket"); // Make the socket listen e = ::listen(sok, 100); // the number of clients that can be queued if (e == -1) throw runtime_error("error listening"); } //============================================================================= Socket *ServerSocket::accept() //============================================================================= // Wait for a client and return the connection socket //============================================================================= { int t = ::accept(sok, 0, 0); if (t == -1) throw runtime_error("error in accept"); return new Socket(t); } //============================================================================= ClientSocket::ClientSocket(const char *host, int port) //============================================================================= { // Create a socket sok = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sok == -1) throw runtime_error("error creating socket"); struct sockaddr_in dest; ::memset(&dest, 0, sizeof(dest)); dest.sin_family = AF_INET; hostent *hp; hp = ::gethostbyname(host); ::memcpy(&dest.sin_addr, hp->h_addr, hp->h_length); if (dest.sin_addr.s_addr == -1) throw runtime_error("cannot find address"); dest.sin_port = htons(port); int result = ::connect(sok, (sockaddr *)&dest, sizeof(sockaddr)); if (result == -1) throw runtime_error("error connecting"); } <|endoftext|>
<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/extensions/renderer/xwalk_extension_renderer_controller.h" #include "base/command_line.h" #include "base/values.h" #include "content/public/renderer/render_thread.h" #include "content/public/renderer/v8_value_converter.h" #include "grit/xwalk_extensions_resources.h" #include "ipc/ipc_channel_handle.h" #include "ipc/ipc_listener.h" #include "ipc/ipc_sync_channel.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebFrame.h" #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h" #include "v8/include/v8.h" #include "xwalk/extensions/common/xwalk_extension_messages.h" #include "xwalk/extensions/common/xwalk_extension_switches.h" #include "xwalk/extensions/renderer/xwalk_extension_client.h" #include "xwalk/extensions/renderer/xwalk_extension_module.h" #include "xwalk/extensions/renderer/xwalk_js_module.h" #include "xwalk/extensions/renderer/xwalk_module_system.h" #include "xwalk/extensions/renderer/xwalk_v8tools_module.h" namespace xwalk { namespace extensions { const GURL kAboutBlankURL = GURL("about:blank"); XWalkExtensionRendererController::XWalkExtensionRendererController( Delegate* delegate) : shutdown_event_(false, false), delegate_(delegate) { content::RenderThread* thread = content::RenderThread::Get(); thread->AddObserver(this); IPC::SyncChannel* browser_channel = thread->GetChannel(); SetupBrowserProcessClient(browser_channel); CommandLine* cmd_line = CommandLine::ForCurrentProcess(); if (cmd_line->HasSwitch(switches::kXWalkDisableExtensionProcess)) LOG(INFO) << "EXTENSION PROCESS DISABLED."; else SetupExtensionProcessClient(browser_channel); } XWalkExtensionRendererController::~XWalkExtensionRendererController() { // FIXME(cmarcelo): These call is causing crashes on shutdown with Chromium // 29.0.1547.57 and had to be commented out. // content::RenderThread::Get()->RemoveObserver(this); } namespace { void CreateExtensionModules(XWalkExtensionClient* client, XWalkModuleSystem* module_system) { const XWalkExtensionClient::ExtensionAPIMap& extensions = client->extension_apis(); XWalkExtensionClient::ExtensionAPIMap::const_iterator it = extensions.begin(); for (; it != extensions.end(); ++it) { XWalkExtensionClient::ExtensionCodePoints* codepoint = it->second; if (codepoint->api.empty()) continue; scoped_ptr<XWalkExtensionModule> module( new XWalkExtensionModule(client, module_system, it->first, codepoint->api)); module_system->RegisterExtensionModule(module.Pass(), codepoint->entry_points); } } } // namespace void XWalkExtensionRendererController::DidCreateScriptContext( blink::WebFrame* frame, v8::Handle<v8::Context> context) { XWalkModuleSystem* module_system = new XWalkModuleSystem(context); XWalkModuleSystem::SetModuleSystemInContext( scoped_ptr<XWalkModuleSystem>(module_system), context); module_system->RegisterNativeModule( "v8tools", scoped_ptr<XWalkNativeModule>(new XWalkV8ToolsModule)); module_system->RegisterNativeModule( "internal", CreateJSModuleFromResource( IDR_XWALK_EXTENSIONS_INTERNAL_API)); delegate_->DidCreateModuleSystem(module_system); CreateExtensionModules(in_browser_process_extensions_client_.get(), module_system); if (external_extensions_client_) { CreateExtensionModules(external_extensions_client_.get(), module_system); } module_system->Initialize(); } void XWalkExtensionRendererController::WillReleaseScriptContext( blink::WebFrame* frame, v8::Handle<v8::Context> context) { v8::Context::Scope contextScope(context); XWalkModuleSystem::ResetModuleSystemFromContext(context); } bool XWalkExtensionRendererController::OnControlMessageReceived( const IPC::Message& message) { return in_browser_process_extensions_client_->OnMessageReceived(message); } void XWalkExtensionRendererController::OnRenderProcessShutdown() { shutdown_event_.Signal(); } void XWalkExtensionRendererController::SetupBrowserProcessClient( IPC::SyncChannel* browser_channel) { in_browser_process_extensions_client_.reset(new XWalkExtensionClient); in_browser_process_extensions_client_->Initialize(browser_channel); } void XWalkExtensionRendererController::SetupExtensionProcessClient( IPC::SyncChannel* browser_channel) { IPC::ChannelHandle handle; browser_channel->Send( new XWalkExtensionProcessHostMsg_GetExtensionProcessChannel(&handle)); // FIXME(cmarcelo): Need to account for failure in creating the channel. external_extensions_client_.reset(new XWalkExtensionClient); extension_process_channel_ = IPC::SyncChannel::Create(handle, IPC::Channel::MODE_CLIENT, external_extensions_client_.get(), content::RenderThread::Get()->GetIOMessageLoopProxy(), true, &shutdown_event_); external_extensions_client_->Initialize(extension_process_channel_.get()); } } // namespace extensions } // namespace xwalk <commit_msg>[Tizen][Runtime] Disable device api in remote web frames.<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/extensions/renderer/xwalk_extension_renderer_controller.h" #include "base/command_line.h" #include "base/values.h" #include "content/public/renderer/render_thread.h" #include "content/public/renderer/v8_value_converter.h" #include "grit/xwalk_extensions_resources.h" #include "ipc/ipc_channel_handle.h" #include "ipc/ipc_listener.h" #include "ipc/ipc_sync_channel.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebFrame.h" #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h" #include "v8/include/v8.h" #include "xwalk/extensions/common/xwalk_extension_messages.h" #include "xwalk/extensions/common/xwalk_extension_switches.h" #include "xwalk/extensions/renderer/xwalk_extension_client.h" #include "xwalk/extensions/renderer/xwalk_extension_module.h" #include "xwalk/extensions/renderer/xwalk_js_module.h" #include "xwalk/extensions/renderer/xwalk_module_system.h" #include "xwalk/extensions/renderer/xwalk_v8tools_module.h" #if defined(OS_TIZEN) #include "xwalk/application/common/constants.h" #endif namespace xwalk { namespace extensions { const GURL kAboutBlankURL = GURL("about:blank"); XWalkExtensionRendererController::XWalkExtensionRendererController( Delegate* delegate) : shutdown_event_(false, false), delegate_(delegate) { content::RenderThread* thread = content::RenderThread::Get(); thread->AddObserver(this); IPC::SyncChannel* browser_channel = thread->GetChannel(); SetupBrowserProcessClient(browser_channel); CommandLine* cmd_line = CommandLine::ForCurrentProcess(); if (cmd_line->HasSwitch(switches::kXWalkDisableExtensionProcess)) LOG(INFO) << "EXTENSION PROCESS DISABLED."; else SetupExtensionProcessClient(browser_channel); } XWalkExtensionRendererController::~XWalkExtensionRendererController() { // FIXME(cmarcelo): These call is causing crashes on shutdown with Chromium // 29.0.1547.57 and had to be commented out. // content::RenderThread::Get()->RemoveObserver(this); } namespace { void CreateExtensionModules(XWalkExtensionClient* client, XWalkModuleSystem* module_system) { const XWalkExtensionClient::ExtensionAPIMap& extensions = client->extension_apis(); XWalkExtensionClient::ExtensionAPIMap::const_iterator it = extensions.begin(); for (; it != extensions.end(); ++it) { XWalkExtensionClient::ExtensionCodePoints* codepoint = it->second; if (codepoint->api.empty()) continue; scoped_ptr<XWalkExtensionModule> module( new XWalkExtensionModule(client, module_system, it->first, codepoint->api)); module_system->RegisterExtensionModule(module.Pass(), codepoint->entry_points); } } #if defined(OS_TIZEN) void CreateExtensionModulesWithoutDeviceAPI(XWalkExtensionClient* client, XWalkModuleSystem* module_system) { const XWalkExtensionClient::ExtensionAPIMap& extensions = client->extension_apis(); XWalkExtensionClient::ExtensionAPIMap::const_iterator it = extensions.begin(); for (; it != extensions.end(); ++it) { XWalkExtensionClient::ExtensionCodePoints* codepoint = it->second; if (codepoint->api.empty() || it->first.find("tizen") == 0) continue; scoped_ptr<XWalkExtensionModule> module( new XWalkExtensionModule(client, module_system, it->first, codepoint->api)); module_system->RegisterExtensionModule(module.Pass(), codepoint->entry_points); } } #endif } // namespace void XWalkExtensionRendererController::DidCreateScriptContext( blink::WebFrame* frame, v8::Handle<v8::Context> context) { XWalkModuleSystem* module_system = new XWalkModuleSystem(context); XWalkModuleSystem::SetModuleSystemInContext( scoped_ptr<XWalkModuleSystem>(module_system), context); module_system->RegisterNativeModule( "v8tools", scoped_ptr<XWalkNativeModule>(new XWalkV8ToolsModule)); module_system->RegisterNativeModule( "internal", CreateJSModuleFromResource( IDR_XWALK_EXTENSIONS_INTERNAL_API)); delegate_->DidCreateModuleSystem(module_system); CreateExtensionModules(in_browser_process_extensions_client_.get(), module_system); if (external_extensions_client_) { #if defined(OS_TIZEN) // On Tizen platform, only local pages can access to device APIs. GURL url = static_cast<GURL>(frame->document().url()); if (!url.SchemeIs(xwalk::application::kApplicationScheme) && !url.SchemeIsFile()) CreateExtensionModulesWithoutDeviceAPI(external_extensions_client_.get(), module_system); else CreateExtensionModules(external_extensions_client_.get(), module_system); #else CreateExtensionModules(external_extensions_client_.get(), module_system); #endif } module_system->Initialize(); } void XWalkExtensionRendererController::WillReleaseScriptContext( blink::WebFrame* frame, v8::Handle<v8::Context> context) { v8::Context::Scope contextScope(context); XWalkModuleSystem::ResetModuleSystemFromContext(context); } bool XWalkExtensionRendererController::OnControlMessageReceived( const IPC::Message& message) { return in_browser_process_extensions_client_->OnMessageReceived(message); } void XWalkExtensionRendererController::OnRenderProcessShutdown() { shutdown_event_.Signal(); } void XWalkExtensionRendererController::SetupBrowserProcessClient( IPC::SyncChannel* browser_channel) { in_browser_process_extensions_client_.reset(new XWalkExtensionClient); in_browser_process_extensions_client_->Initialize(browser_channel); } void XWalkExtensionRendererController::SetupExtensionProcessClient( IPC::SyncChannel* browser_channel) { IPC::ChannelHandle handle; browser_channel->Send( new XWalkExtensionProcessHostMsg_GetExtensionProcessChannel(&handle)); // FIXME(cmarcelo): Need to account for failure in creating the channel. external_extensions_client_.reset(new XWalkExtensionClient); extension_process_channel_ = IPC::SyncChannel::Create(handle, IPC::Channel::MODE_CLIENT, external_extensions_client_.get(), content::RenderThread::Get()->GetIOMessageLoopProxy(), true, &shutdown_event_); external_extensions_client_->Initialize(extension_process_channel_.get()); } } // namespace extensions } // namespace xwalk <|endoftext|>